输出:
foobar init
foo init

但这并不意味着 Bar 类不能继承。最终 FooBar 类的实例也是 Bar 类和 Foo 类的实例。
print(isinstance(a,FooBar))
print(isinstance(a,Foo))
print(isinstance(a,Bar))
输出:
True
True
True

Section 38.8: 属性
Python 类支持属性,这些属性看起来就像普通的对象变量,但可以附加自定义行为和文档。
class MyClass(object):
def __init__(self):
self._my_string = ""
@property
def string(self):
"""A profoundly important string."""
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

除了上述有用的语法外,属性语法还允许为这些属性添加验证或其他增强功能。这在公共应用程序接口(Public API)中尤其有用--在公共应用程序接口中,应为用户提供一定程度的帮助。
属性的另一个常见用途是使类能够显示 “虚拟属性”--实际上并不存储的属性,只有在请求时才会计算。
class Character(object):
def __init__(self, name, max_hp):
self._name = name
self._hp = max_hp
self._max_hp = max_hp
# Make hp read only by not providing a set method
@property
def hp(self):
return self._hp
# Make name read only by not providing a set method
@property
def name(self):
return self.name
def take_damage(self, damage):
self._hp -= damage
self._hp = 0 if self.hp <0 else self.hp
@property
def is_alive(self):
return self.hp != 0
@property
def is_wounded(self):
return self.hp < self._max_hp if self.hp > 0 else False
@property
def is_dead(self):
return not self.is_alive
bilbo = Character('Bilbo Baggins', 100)
bilbo.hp
# out : 100
bilbo.hp = 200
# out : AttributeError: can't set attribute
# hp attribute is read only.
bilbo.is_alive
# out : True
bilbo.is_wounded
# out : False
bilbo.is_dead
# out : False
bilbo.take_damage( 50 )
bilbo.hp
# out : 50
bilbo.is_alive
# out : True
bilbo.is_wounded
# out : True
bilbo.is_dead
# out : False
bilbo.take_damage( 50 )
bilbo.hp
# out : 0
bilbo.is_alive
# out : False
bilbo.is_wounded
# out : False
bilbo.is_dead
# out : True

