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

Python 没有多态

2016-04-26 19:43 615 查看
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'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: