您的位置:首页 > 编程语言 > Python开发

python 多继承(2)

2009-09-17 14:16 337 查看
from:  http://www.chinesepython.org/pythonfoundry/tut2.3/tmp/multiple.html

 

9.5.1 多继承 Multiple Inheritance

Python supports a limited form of multiple inheritance as well. A class definition with multiple base classes looks as follows:

Python同样有限的支持多继承形式。多继承的类定义形如下例:

 

class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>


The only rule necessary to explain the semantics is the resolution rule used for class attribute references. This is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on.

这里唯一需要解释的语义是解析类属性的规则。顺序是深度优先,从左到右。因此,如果在 DerivedClassName (示例中的派生类)中没有找到某个属性,就会搜索 Base1 ,然后(递归的)搜索其基类,如果最终没有找到,就搜索 Base2,以此类推。

(To some people breadth first -- searching Base2 and Base3 before the base classes of Base1 -- looks more natural. However, this would require you to know whether a particular attribute of Base1 is actually defined in Base1 or in one of its base classes before you can figure out the consequences of a name conflict with an attribute of Base2. The depth-first rule makes no differences between direct and inherited attributes of Base1.)

(有些人认为广度优先--在搜索Base1的基类之前搜索Base2和
Base3
--看起来更为自然。然而,如果Base1和Base2之间发生了命名冲突,你需要了解这个属性是定义于Base1还是Base1的基类中。而深度优先不区分属性继承自基类还是直接定义。)

It is clear that indiscriminate use of multiple inheritance is a maintenance nightmare, given the reliance in Python on conventions to avoid accidental name conflicts. A well-known problem with multiple inheritance is a class derived from two classes that happen to have a common base class. While it is easy enough to figure out what happens in this case (the instance will have a single copy of ``instance variables'' or data attributes used by the common base class), it is not clear that these semantics are in any way useful.

显然不加限制的使用多继承会带来维护上的噩梦,因为 Python 中只依靠约定来避免命名冲突。多继承一个很有名的问题是派生继承的两个基类都是从同一个基类继承而来。目前还不清楚这在语义上有什么意义,然而很容易想到这会造成什么后果(实例会有一个独立的“实例变量”或数据属性复本作用于公共基类。)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息