现在的位置: 首页 > 综合 > 正文

python中的多态

2013年09月11日 ⁄ 综合 ⁄ 共 983字 ⁄ 字号 评论关闭

多态性

是允许将父对象设置成为和一个或多个它的子对象相等的技术,比如Parent:=Child; 多态性使得能够利用同一类(基类)类型的指针来引用不同类的对象,以及根据所引用对象的不同,以不同的方式执行相同的操作.

c++中多态更容易理解的概念为

允许父类指针或名称来引用子类对象,或对象方法,而实际调用的方法为对象的类类型方法。

--------------以上内容来自百度百科----------------


python不支持多态

python是一种动态语言,参数在传入之前是无法确定参数类型的,看下面例子:

class A:
    def prt(self):
        print "A"

class B(A):
    def prt(self):
        print "B"
        
class C(A):
    def prt(self):
        print "C"
       
class D(A):
    pass

class E:
    def prt(self):
        print "E"

class F:
    pass

def test(arg):
    arg.prt()

a = A()
b = B()
c = C()
d = D()
e = E()
f = F()

test(a)
test(b)
test(c)
test(d)
test(e)
test(f)

输出结果:

A
B
C
A
E
Traceback (most recent call last):
  File "/Users/shikefu678/Documents/Aptana Studio 3 Workspace/demo/demo.py", line 33, in <module>
    test(a),test(b),test(c),test(d),test(e),test(f)
  File "/Users/shikefu678/Documents/Aptana Studio 3 Workspace/demo/demo.py", line 24, in test
    arg.prt()
AttributeError: F instance has no attribute 'prt'

乍一看似乎python支持多态,调用test(a),test(b),test(c),test(d)时工作的很好,但是下边就大不一样了。调用test(e)时,python只是调用e的prt方法,并没有判断e是否为A子类的对象(事实上,定义test方法时也没有指定参数的类型,python根本无法判断)。调用test(f)时报错,原因很很简单,f没有prt方法。

抱歉!评论已关闭.