虽然试图拿出一个手工类卡片游戏 我遇到了从属性一个奇怪的行为类属性不工作正常(蟒蛇)
,如果我尝试设置self.number
所看到下面它不会显示合适的输出 但如果我通过一个函数进行相同的参数total()
它工作正常
我的问题是:为什么属性self.number
没有得到的len(self.cards)
价值?
class Hand (object):
def __init__(self,number=0,cards=[]):
self.cards=cards
self.number=len(self.cards)
def total(self):
return len(self.cards)
hand=Hand()
hand.cards.append(9)
print hand.cards
print len(hand.cards)
print hand.number
print hand.total()
output:
[9]
1
0 #I want this to be equal to 1
1
因此对于所有a:__init __(a):self.a = a仅在启动期间被检查和使用 感谢您的帮助:) –
@Jared @ @ property'装饰器节省了时间和精力,事情,自动给我'set'和'get'命令,是吗?人们可以通过手动定义“财产”的方面来实现相同的目标吗?谢谢! – patrick
@patrick:@property装饰器使它装饰成一个getter的方法。该类的用户将能够像访问属性一样访问“数字”。为了制作一个setter,你用'@ attribute_name.setter'来装饰setter方法(在这种情况下,它将是'@ number.setter')。 –