gpt4 book ai didi

python - 编写安全、强制的 Python 类

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:58 24 4
gpt4 key购买 nike

我正在尝试使用尽可能最好和最安全的约定来实现一个类。有没有更好的办法

a) 防止对属性进行外部编辑,以及

b) 对这些属性强制执行某些约束,例如有效等级和花色?

class Card:

__ranks = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']
__suits = ['Heart', 'Club', 'Diamond', 'Spade']

def __init__(self, rank, suit):
assert rank in self.__ranks
assert suit in self.__suits
self.__rank = rank
self.__suit = suit

def getRank(self):
return self.__rank

def getSuit(self):
return self.__suit

最佳答案

你可以使用命名元组,这样对象是不可变的

>>> from collections import namedtuple
>>> Card = namedtuple('Card','rank,suit')
>>> acard = Card('10','D')
>>> acard.suit
'D'
>>> acard.rank
'10'
>>> acard.rank='H'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
>>>

有关详细信息,请参阅 namedtuple 文档(在 collections 模块中,https://docs.python.org/2/library/collections.html)

关于python - 编写安全、强制的 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38966762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com