17 1月 2009

[Python] 實作出 class中的 virtual function

  在Python的世界裡,Class並沒有pure virtual function的概念,所以也沒有所謂的virtual class,但是實際上Python提供了一套機制去模擬virtual function的概念,雖然不像C++嚴謹到無法使用virtual class去宣告出一個實體物件,但是至少在使用此function時,可以丟出一個Error Message出來。

  Python提供的方法就是,你可以在pure virtual function裡,丟一個Error message NotImplementedError出來,夠簡單了吧… 其實自己隨便丟一個也可以達到相同的目的=_=,只是Python提供了個error type,讓我們用起來更有感覺。不過,沒魚蝦也好啦~

以下是範例程式碼…

class virtualClass:
def __init__(self):
pass
def virtualMethod(self): #virtual function.
raise NotImplementedError( "virtualMethod is virutal! Must be overwrited." )

class subClass( virtualClass ):
def __init__(self):
virtualClass.__init__(self)
pass
def virtualMethod(self): #overwrite the virtual function.
print 'subClass! have overwirted the virtualMethod() success.'

v = virtualClass()
v.virtualMethod()

s = subClass()
s.virtualMethod()

1 則留言:

匿名 提到...

it is confusing and may not be needed,

it has exception error
only when calling v.virtualMethod()

it does not mean we must overwrite the method,
following code does not implement the m1 has no exceptions at all.

so, I think raise NotImplementedError is not meaningful

#! /usr/bin/env python

class B(object):
def __init__(self):
pass
def m1(self):
raise NotImplementedError( "B::1 Must be overwrited." )

class D( B ):
def __init__(self):
super(D,self).__init__()

#def m1(self):
# print 'D::m1 have overwirted the B::m1 success.'

def m2(self):
print 'D::m2'


b = B()
#b.m1() # cannot be implemented

d = D()
d.m2() #no problem