Python物产
示例
Python类支持属性,这些属性看起来像常规的对象变量,但是可以附加自定义行为和文档。
class MyClass(object):
def __init__(self):
self._my_string= ""
@property
def string(self):
"""一个非常重要的字符串。"""
return self._my_string
@string.setter
def string(self, new_value):
assert isinstance(new_value, str), \
"Give me a string, not a %r!" % type(new_value)
self._my_string= new_value
@string.deleter
def x(self):
self._my_string= None对象的类的MyClass会出现有有一个属性.string,但它的行为是现在严格控制:
mc = MyClass() mc.string = "String!" print(mc.string) del mc.string
除了上述有用的语法外,属性语法还允许进行验证或将其他增强功能添加到这些属性中。这对于公共API可能特别有用-应向用户提供一定程度的帮助。
属性的另一种常见用法是使类能够呈现“虚拟属性”,即实际上并未存储但仅在请求时才计算的属性。
class Character(object):
def __init__(name, max_hp):
self._name= name
self._hp= max_hp
self._max_hp= max_hp
#通过不提供设置方法使hp只读
@property
def hp(self):
return self._hp
#通过不提供set方法使名称只读
@property
def name(self):
return self.name
def take_damage(self, damage):
self.hp-= damage
self.hp= 0 ifself.hp<0 else self.hp
@property
def is_alive(self):
returnself.hp!= 0
@property
def is_wounded(self):
returnself.hp<self.max_hpifself.hp> 0 else False
@property
def is_dead(self):
return not self.is_alive
bilbo = Character('Bilbo Baggins', 100)
bilbo.hp
#出:100
bilbo.hp = 200
#out:AttributeError:无法设置属性
#hp属性是只读的。
bilbo.is_alive
#出:真
bilbo.is_wounded
#出:错误
bilbo.is_dead
#出:错误
bilbo.take_damage( 50 )
bilbo.hp
#出:50
bilbo.is_alive
#出:真
bilbo.is_wounded
#出:真
bilbo.is_dead
#出:错误
bilbo.take_damage( 50 )
bilbo.hp
#出:0
bilbo.is_alive
#出:错误
bilbo.is_wounded
#出:错误
bilbo.is_dead
#出:真