在python中,如何处理可变的类属性

2024-10-02 00:38:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在执行以下Python代码:

class Pet :
    kind = 'dog'    # class variable shared by all instances
    tricks = []

    def __init__(self, name) :
        self.name = name # instance variable unique to each instance
    def changePet(self, newPet) :
        self.kind = newPet
    def addTricks(self, tricks) :
        self.tricks.append(tricks)

pet1 = Pet('mypet')
pet2 = Pet('yourpet')
print 'pet1 kind ::: ', pet1.kind;print 'pet2 kind ::: ', pet2.kind
print 'pet1 name ::: ', pet1.name;print 'pet2 name ::: ', pet2.name

Pet.kind = 'cat'
print 'changed Pet.kind to cat'
print 'pet1 kind ::: ', pet1.kind;print 'pet2 kind ::: ', pet2.kind

#changing pet#1 kind does not change pet#2 kind
pet1.changePet('parrot')
print 'changed pet1.kind to parrot'
print 'pet1 kind ::: ', pet1.kind;print 'pet2 kind ::: ', pet2.kind

pet1.addTricks('imitate')
pet2.addTricks('roll over')
print 'pet1 tricks ::: ', pet1.tricks;print 'pet2 tricks ::: ', pet2.tricks

print Pet.__dict__
print pet1.__dict__
print pet2.__dict__

输出是根据我在网上找到的解释。输出如下

^{pr2}$

现在我的问题是为什么可变类对象和非可变类对象的处理方式不同


Tags: toinstancenameselfdefvariabledictclass
1条回答
网友
1楼 · 发布于 2024-10-02 00:38:18

我不确定他们有没有区别对待。你只是在对它们执行不同的操作。在

changePet的情况下,将先前未定义的self.kind分配给一个值。现在,当python试图找到pet1.kind时,它会立即找到它。当查找pet2.kind时,它没有找到它。但是,它确实找到了find Pet.kind,因此它返回该值。在

addTricks的情况下,您试图使self.tricks发生突变。因为它不存在,所以会给您一个对Pet.tricks的引用。因此,当您在self.tricks上调用append()时,您有效地调用了Pet.tricks.append(),而不是{}。在

为了澄清这一点:

def changePet(self, newPet) :
    self.kind = newPet
def addTricks(self, tricks) :
    self.tricks.append(tricks)

实际上相当于:

^{pr2}$

为了证明python对待可变表和非可变表没有区别,我们需要更改您的方法,以便它们执行类似的操作:

def changePet(self, newPet) :
    self.kind = newPet

def addTricks(self, tricks):
    # assign self.tricks to a new value where we previously only mutated it!
    # note: list(self.tricks) returns a copy
    self.tricks = list(self.tricks)
    self.tricks.append(tricks)

现在,当我们再次运行代码时,会得到以下输出:

pet1 kind :::  dog
pet2 kind :::  dog
pet1 name :::  mypet
pet2 name :::  yourpet
changed Pet.kind to cat
pet1 kind :::  cat
pet2 kind :::  cat
changed pet1.kind to parrot
pet1 kind :::  parrot
pet2 kind :::  cat
pet1 tricks :::  ['imitate']
pet2 tricks :::  ['roll over']
{'__module__': '__main__', 'tricks': [], 'kind': 'cat', 'addTricks': <function addTricks at 0x02A33C30>, 'changePet': <function changePet at 0x02A33BF0>, '__doc__': None, '__init__': <function __init__ at 0x02A33BB0>}
{'tricks': ['imitate'], 'kind': 'parrot', 'name': 'mypet'}
{'tricks': ['roll over'], 'name': 'yourpet'}

相关问题 更多 >

    热门问题