看了人家老哥的栗子,一下对结果就懵逼了,然后掰开揉碎,一顿整 ,看代码的执行顺序。 这才看明白。这老哥挺牛逼的 !面向对象还得整。
class PoloBlogObjectTest:
sum = 0
def __init__(self, name, age):
self.name = name
self.age = age
print(f'加1之前{PoloBlogObjectTest.sum}')
PoloBlogObjectTest.sum += 1
print(f'加1之后{PoloBlogObjectTest.sum}')
def printNameAge(self):
print(self.name, self.age)
print(f'poloTest1实例化之前{PoloBlogObjectTest.sum}先读类属性sum')
poloTest1 = PoloBlogObjectTest("小菠萝一号", 24)
print(f'poloTest1实例化之后{PoloBlogObjectTest.sum}')
poloTest1.printNameAge()
print('=======')
print(f'poloTest2实例化之前{PoloBlogObjectTest.sum}')
poloTest2 = PoloBlogObjectTest("小菠萝二号", 14)
print(f'poloTest2实例化之前{PoloBlogObjectTest.sum}')
poloTest2.printNameAge()
print(PoloBlogObjectTest.sum)
运行顺序和结果
poloTest1实例化之前0先读类属性sum
加1之前0
加1之后1
poloTest1实例化之后1
小菠萝一号 24
=======
poloTest2实例化之前1
加1之前1
加1之后2
poloTest2实例化之前2
小菠萝二号 14
2
Process finished with exit code 0
https://www.cnblogs.com/poloyy/p/15178468.html
|