Skip to main content
 首页 » 编程设计

python之类属性不能正常工作(python)

2025年05月04日15虾米姐

在尝试为纸牌游戏设计 Hand 类时 我遇到了一个属性的奇怪行为

如果我尝试设置 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 

请您参考如下方法:

属性 self.number 在实例化时设置,请改用属性。

class Hand (object): 
    def __init__(self, cards=None): 
        self.cards = cards or [] 
 
    @property 
    def number(self): 
        return len(self.cards) 
 
    def total(self): 
        return len(self.cards)