您的位置:首页 > 编程语言 > C语言/C++

Python中C++类特性的实现原理

2014-12-05 14:39 399 查看
<span style="font-size:18px;">#python类的特性</span>
<span style="font-size:18px;">#而且python还可以实现函数的重载,通过不同的参数来做不同的内部实现</span>
<span style="font-size:18px;">#def overload(*args):</span>
<span style="font-size:18px;">#<span style="white-space:pre">	</span>def overload1():</span>
<span style="font-size:18px;">#<span style="white-space:pre">		</span>print("No args")</span>
<span style="font-size:18px;">#<span style="white-space:pre">	</span>def overload2(x):</span>
<span style="font-size:18px;">#<span style="white-space:pre">		</span>print("one args")</span>
<span style="font-size:18px;">#<span style="white-space:pre">	</span>def overload3(x,y):</span>
<span style="font-size:18px;">#<span style="white-space:pre">		</span>print("two args")</span>
<span style="font-size:18px;">#<span style="white-space:pre">	</span>if len(args) == 0:</span>
<span style="font-size:18px;">#<span style="white-space:pre">		</span>overload1()</span>
<span style="font-size:18px;">#<span style="white-space:pre">	</span>elif len(args) == 1:</span>
<span style="font-size:18px;">#<span style="white-space:pre">		</span>overload2(*args)</span>
<span style="font-size:18px;">#<span style="white-space:pre">	</span>else len(args) == 2:</span>
<span style="font-size:18px;">#<span style="white-space:pre">		</span>overload3(*args)</span>
<span style="font-size:18px;">
class Point:
x = 100
y = 200
def __init__(self, *args):
try:
self.x = args[0]
self.y = args[1]
except ValueError, e:
print(e.message)
except IndexError, e:
print(e.message)

def trace(self):
print 'x=%d y=%d' % (self.x, self.y)

def overload(self):
print('Point overload')

def baseMethod(self):
print('base method!!!!!!')

<strong><span style="color:#ff0000;">    #接口预留,本处没有实现doVirtual,经由子类来实现
def delegate(self):
self.doVirtual()</span></strong>

class Point3D(Point):
z = 0
def __init__(self, *args):
try:
Point.__init__(self, *args)
self.z = args[2]
except IndexError, e:
print e.message

<strong><span style="color:#ff0000;">    #函数重写override
def trace(self):
Point.trace(self)
print 'z=%d' % self.z</span></strong>

<span style="color:#ff0000;"><strong>   #函数遮挡
def overload(self, x):
print('Point3D visible')</strong></span>

class PointProvider(Point):
def __init__(self, *argc):
Point.__init__(self, *argc)

def doVirtual(self):
print 'Implements doVirtual!'

if __name__ == '__main__':
p1 = Point(10,20)
p1.k=100 #变相的给增加了成员
pk = 'p1.k=%d' % (p1.k)
print(pk)
p1.trace()

p2 = Point(1,1)
p2.overload()
#compiler error!!!
#print(p2.k)

p = Point3D(1,2,3)
p.trace()
#看不见基类的overload了,必须要传入一个参数
p.overload(100)

p2.baseMethod()

pp = PointProvider(10,20)
pp.delegate()</span>


所以综上所示:

python可以实现类的继承、重载、重写(多态)、函数覆盖(隐藏基类函数)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: