Section 38.5: 新样式类 vs. 旧样式类
Python 2.2 引入了新样式类来统一类和类型。它们继承自顶层的 object 类型。新样式类是用户定义的类型,与内置类型非常相似。
# new-style class
class New(object):
pass
# new-style instance
new = New()
new.__class__
# <class '__main__.New'>
type(new)
# <class '__main__.New'>
issubclass(New, object)
# True

旧式类不继承于 object。旧式实例总是通过内置的 instance 类型来实现。
# old-style class
class Old:
pass
# old-style instance
old = Old()
old.__class__
# <class __main__.Old at ...>
type(old)
# <type 'instance'>
issubclass(Old, object)
# False
在 Python 3 中,旧式的类被删除了。
Python 3 中的新式类隐式地继承自 object,因此不再需要指定 MyClass(object)。
class MyClass:
pass
my_inst = MyClass()
type(my_inst)
# <class '__main__.MyClass'>
my_inst.__class__
# <class '__main__.MyClass'>
issubclass(MyClass, object)
# True

Section 38.6: 类方法:替代初始化器
类方法是构建类实例的另一种方法。举个例子来说明。
假设我们有一个相对简单的 Person 类:
class Person(object):
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.full_name = first_name + " " + last_name
def greet(self):
print("Hello, my name is " + self.full_name + ".")
如果能提供一种方法来构建该类的实例,指定全名而不是分别指定姓和名,可能会很方便。一种方法是让 last_name 成为一个可选参数,并假设如果没有给出该参数,我们就传递了全名:
class Person(object):
def __init__(self, first_name, age, last_name=None):
if last_name is None:
self.first_name, self.last_name = first_name.split(" ", 2)
else:
self.first_name = first_name
self.last_name = last_name
self.full_name = self.first_name + " " + self.last_name
self.age = age
def greet(self):
print("Hello, my name is " + self.full_name + ".")
不过,这段代码有两个主要问题:
- 参数
first_name和last_name现在会引起误解,因为您可以为first_name输入全名。此外,如果有更多的情况和/或更多的参数具有这种灵活性,if/elif/else分支就会很快变得很烦人。 - 虽然不那么重要,但仍值得指出:如果 last_name 是
None,但first_name没有通过空格分割成两个或多个内容,该怎么办?我们又多了一层输入验证和/或异常处理...
输入类方法。我们将创建一个名为 from_full_name 的单独初始化器,并使用(内置的) classmethod 装饰器对其进行装饰,而不是使用单一的初始化器。
class Person(object):
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.full_name = first_name + " " + last_name
@classmethod
def from_full_name(cls, name, age):
if " " not in name:
raise ValueError
first_name, last_name = name.split(" ", 2)
return cls(first_name, last_name, age)
def greet(self):
print("Hello, my name is " + self.full_name + ".")
注意 from_full_name 的第一个参数是 cls 而不是 self。类方法应用于整个类,而不是给定类的实例(self 通常表示实例)。因此,如果 cls 是我们的 Person 类,那么 from_full_name 类方法的返回值就是 Person(first_name, last_name, age),它会使用 Person 的 __init__ 来创建 Person 类的实例。特别是,如果我们要创建 Person 的子类 Employee,那么 from_full_name 也会在 Employee 类中工作。
为了证明它的工作原理符合预期,让我们在不使用 __init__ 分支的情况下,用多种方法创建 Person 的实例:
>>> bob = Person("Bob", "Bobberson", 42)
>>> alice = Person.from_full_name("Alice Henderson", 31)
>>> bob.greet()
Hello, my name is Bob Bobberson.
>>> alice.greet()
Hello, my name is Alice Henderson.

其他参考资料:
- Python @classmethod 和 @staticmethod 适合初学者吗?
- https://docs.python.org/2/library/functions.html#classmethod
- https://docs.python.org/3.5/library/functions.html#classmethod
Section 38.7: 多重继承
Python 使用 C3 线性化算法来确定类属性(包括方法)的解析顺序。这就是所谓的方法解析顺序 (MRO)。
下面是一个简单的例子:
class Foo(object):
foo = 'attr foo of Foo'
class Bar(object):
foo = 'attr foo of Bar' # we won't see this.
bar = 'attr bar of Bar'
class FooBar(Foo, Bar):
foobar = 'attr foobar of FooBar'
现在,如果我们实例化 FooBar,如果我们查找 foo 属性,我们会发现 Foo 的属性被首先找到
fb = FooBar()
和
>>> fb.foo
'attr foo of Foo'

这是 FooBar 的 MRO:
FooBar.mro()
[<class '__main__.FooBar'>, <class '__main__.Foo'>, <class '__main__.Bar'>, <type 'object'>]

可以简单地说,Python 的 MRO 算法是:
深度优先(例如,先是 FooBar,然后是 Foo),除非共享的父(对象)被子(Bar)阻塞,并且不允许循环关系。
例如,Bar 不能从 FooBar 继承,而 FooBar 从 Bar 继承。
有关 Python 中的综合示例,请参阅维基百科条目。
super 可以获取父类的特征。
class Foo(object):
def foo_method(self):
print "foo Method"
class Bar(object):
def bar_method(self):
print "bar Method"
class FooBar(Foo, Bar):
def foo_method(self):
super(FooBar, self).foo_method()
当每个类都有自己的 __init__ 方法时,如果我们尝试多重继承,那么只有先继承的类的 __init__ 方法才会被调用。
下面的例子中,只有 Foo 类的初始方法被调用,Bar 类的初始方法没有被调用
class Foo(object):
def __init__(self):
print("foo init")
class Bar(object):
def __init__(self):
print("bar init")
class FooBar(Foo, Bar):
def __init__(self):
print("foobar init")
super(FooBar, self).__init__()
a = FooBar()
输出:
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

