变量设为私有之后,编写set和get函数实现对私有变量的访问。将set、get函数传入property(属性函数),实现可以通过(对象名.变量名)的形式访问和修改。
方法一:
property的使用:变量名 = property()
class Person():
def get_Age(self):
return self.__age
def set_Age(self,age):
if (age > 0 & age<150):
self.__age = age
else:
print('年龄非法')
pass
def __init__(self,name,age):
self.__name = name
self.__age = age
pass
def __str__(self):
return('{}年龄{}'.format(self.__name,self.__age))
age = property(get_Age,set_Age)
person1 = Person('Nick',21)
print(person1.age)
person1.age = 22
print(person1.age)
输出:
21
22
方法二:
class Person():
@property
def age(self):
return self.__age
@age.setter
def age(self,parms):
if (parms > 0 & parms<150):
self.__age = parms
else:
print('年龄非法')
pass
def __init__(self,name,age):
self.__name = name
self.__age = age
pass
person1 = Person('Nick',21)
print(person1.age)
person1.age = 22
print(person1.age)
输出:
21
22