#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# ithomer.net
#
class A:
def pout(self):
print "A"
class B(A):
def pout(self):
print "B"
class C(A):
def pout(self):
print "C"
class D(A):
pass
class E:
def pout(self):
print "E"
class F:
pass
def test(arg):
arg.pout()
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 "/home/homer/workspace/myPython/com/homer/example.py", line 44, in <module>
test(f)
File "/home/homer/workspace/myPython/com/homer/example.py", line 30, in test
arg.pout()
AttributeError: F instance has no attribute 'pout'
a,b,c,d都是A类型的变量,所以可以得到预期的效果(从java角度的预期)
e并不是A类型的变量但是根据鸭子类型,走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子,e有pout方法,所以在test方法中e就是一个A类型的变量,f没有pout方法,所以f不是A类型的变量。