问题:请写出以下代码的输出结果
class Person:
childrens = 1 #类属性
def __init__(self):
pass
t1 = Person() #实例对象
t2 = Person() #实例对象
t2.childrens = 2 #实例属性
print('p1: ', t1.childrens)
print('p2: ', t2.childrens)
print('Person: ', Person.childrens)
输出结果:
p1: 1
p2: 2
Person: 1
这个问题涉及到的一个知识点:如果实例属性和类属性相同,实例属性会覆盖类属性,python在访问属性的时候,会先对实例对象进行搜索,如果实例对象没有对应的属性,再搜索类属性。
那如果将属性换为可变类型的话,结果会怎样:
class Person:
childrens = []
def __init__(self):
pass
t1 = Person()
t2 = Person()
t2.childrens.append('Tony') #在类属性上进行操作
print('p1: ', t1.childrens)
print('p2: ', t2.childrens)
print('Person: ', Person.childrens)
运行结果:
p1: ['Tony']
p2: ['Tony']
Person: ['Tony']
从代码中可以看出,t2 实例对象是在对类属性进行操作修改,即python直接获取到了类属性,所以输出结果都是一样的。