我正在执行以下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}$现在我的问题是为什么可变类对象和非可变类对象的处理方式不同
我不确定他们有没有区别对待。你只是在对它们执行不同的操作。在
在
changePet
的情况下,将先前未定义的self.kind
分配给一个值。现在,当python试图找到pet1.kind
时,它会立即找到它。当查找pet2.kind
时,它没有找到它。但是,它确实找到了findPet.kind
,因此它返回该值。在在}。在
addTricks
的情况下,您试图使self.tricks
发生突变。因为它不存在,所以会给您一个对Pet.tricks
的引用。因此,当您在self.tricks
上调用append()
时,您有效地调用了Pet.tricks.append()
,而不是{为了澄清这一点:
实际上相当于:
^{pr2}$为了证明python对待可变表和非可变表没有区别,我们需要更改您的方法,以便它们执行类似的操作:
现在,当我们再次运行代码时,会得到以下输出:
相关问题 更多 >
编程相关推荐