1. 程式人生 > >python面向物件程式碼示例(python2.7)

python面向物件程式碼示例(python2.7)

以python2.7為例說明

【示例一】指定呼叫哪個物件的函式

>>> class Foo(object):
        def func(self):
            print "foo's function"

>>> class Bar(Foo):
        def func(self):
            print "bar's function"

>>> obj = Bar()
>>> # this will call Bar's function
>>> 
obj.func() bar's function >>> obj.__class__ = Foo # 指定該物件所屬的類 >>> obj.func() foo's function >>>

【示例二】直接呼叫類的例項,而不是呼叫例項的方法

>>> class Hi(object):
        def __init__(self, x, y):
            self.__x = x
            self.__y = y
        def myfunc(self):
            print
"x=", self.__x, "b=", self.__y >>> h = Hi("good", "job") >>> h.myfunc() # 此處呼叫該例項的方法 x= good b= job >>> h("ok") # 無法直接呼叫此類的例項 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-22
-d4380afdeffd> in <module>() ----> 1 h("ok") TypeError: 'Hi' object is not callable >>> # 如何能直接呼叫例項?這裡有個關鍵的方法__call__()能實現此類的例項可直接呼叫 >>> class Hi(object): def __init__(self, x, y): self.__x = x self.__y = y def myfunc(self): print "x=", self.__x, "b=", self.__y def __call__(self, arg): print "call:", arg + self.__x + self.__y >>> h2 = Hi("nice", "guy") >>> h2.myfunc() x= nice b= guy >>> h2("yeah~") # __call__ 函式能實現此類的例項可直接呼叫 call: yeah~niceguy

好了,就寫到這裡,看官們覺得漲知識了,請在文章左側點個贊 ^_^