@property装饰器
在前面《面向对象的三大特性》中说过了Python中属性和方法访问权限的问题,虽然不建议将属性设置为私有的,但是如果直接将属性暴露给外界也是有问题的。这里通过属性的getter(访问器)和setter(修改器)方法进行对应的操作,使用@property包装器来包装getter和setter方法对属性进行访问。
eg.@property装饰器
class Victory(object):
def __init__(self, city, hero):
self._city = city
self._hero = hero
# 访问器 - getter方法
@property
def city(self):
return self._city
# 访问器 - getter方法
@property
def hero(self):
return self._hero
# 修改器 - setter方法
@hero.setter
def hero(self, hero):
self._hero = hero
def cheer(self):
print('%s加油' % self._city)
print('感谢%s' % self._hero)
def main():
victory = Victory('武汉', '钟南山')
victory.cheer()
print(victory.hero)
victory.hero = '全体医护人员'
victory.cheer()
print(victory.hero)
# victory.city = 'abc' # AttributeError: can't set attribute
if __name__ == '__main__':
main()
运行结果:
__slot__
Python是一门动态语言,通常动态语言允许我们在程序运行时给对象绑定新的属性和方法,当然也可以对已经绑定的属性和方法进行解绑。但是如果需要限定自定义类型的对象只能绑定某些属性,可以通过在类中定义__slot__变量来进行限定。
class Victory(object):
# 限定Person对象只能绑定_name, _age和_gender属性
__slots__ = ('_city', '_hero','_open')
def __init__(self, city, hero):
self._city = city
self._hero = hero
# 访问器 - getter方法
@property
def city(self):
return self._city
# 访问器 - getter方法
@property
def hero(self):
return self._hero
# 修改器 - setter方法
@hero.setter
def hero(self, hero):
self._hero = hero
def cheer(self):
print('%s加油' % self._city)
print('感谢%s' % self._hero)
def main():
victory = Victory('武汉', '钟南山')
victory.cheer()
victory._open = True
print(victory._open)
victory._abc = false
# AttributeError: 'Victory' object has no attribute '_abc'
if __name__ == '__main__':
main()
运行结果: