class Person:
def __init__(self,name,age=18):
self.name = name
self.age = age
def growup(self,inc=1):
if 0 < self.age < 150:
self.age += inc
tom = Person('tom')
tom.age = 180 #破坏函数中if判断的本意
print(tom.age)
#改造(私有变量)
print('='*50)
class Person2:
def __init__(self,name,age=18):
self.name = name
self.__age = age
def growup(self,inc=1):
if 0 < self.__age < 150:
self.__age += inc
def getage(self):
return self.__age
tom2 = Person2('tom2')
print(tom2.getage())
print('='*50)
print(tom2.age)
运行结果:
180
==================================================
18
==================================================
Traceback (most recent call last):
File "/home/yzx/PycharmProjects/python/t5.py", line 32, in <module>
print(tom2.age)
AttributeError: 'Person2' object has no attribute 'age'
Process finished with exit code 1