2016-12-02 108 views
0

第一天學習Python的,請原諒的基本問題。Python入門:實現虛擬方法

假設我一直在考慮一個對象,它包含了我需要實現一個未實現的方法,e.g:

class myclass(): 
    def __init__(self) 
    self.unimplementedmethod = False 

什麼是實例化對象來實現這一正確的方法是什麼?我不想以任何方式改變基類。 我已經試驗過,發現下面的代碼似乎可行,但它是正確的還是很好的風格?

def methodimplementation(): 
    print("method called") 

myobject = myclass() 
myobject.unimplementedmethod=methodimplementation 

這是正確的道路嗎?或者我應該做一些不同的事情,比如先創建一個派生類,然後實現其中的方法,然後基於派生類實例化一個對象?什麼是最佳做法?

+1

你應該繼承的類,是的。和未實現的方法不應該有值'FALSE',而是(如果有的話)應該返回單'NotImplemented'實際的方法。 – L3viathan

+0

Thankyou。這是來自開源項目「Printrun」。 P.S該死的快! –

+1

我知道這是不是一個代碼審查,但你並不需要'()''中MyClass的類():'(但是,你應該永遠繼承'object'如果你正在寫的Python 2)。 – Tobias

回答

1

您需要子類的基類:

class myclass(): 
    def some_method(): 
     raise NotImplementedError 

class my_subclass(myclass): 
    def some_method(): 
     print("method called") 
0

你想創建一個abstract base class。爲此,您需要在您的基類中繼承abc.ABCMeta。然後將該方法定義爲抽象,您需要用@abstractmethod對其進行修飾。例如:

class MyChildClass(BaseClass): 
    def my_method(): 
     print 'my method' 
0

好點的方法是使用的子類,但是如果你不能做到這一點,這裏是進入self道:

from abc import ABCMeta, abstractmethod 

class BaseClass(ABCMeta): 
    @abstractmethod 
    def my_method(): 
     pass 

然後,你可以創建子類從在一個類中沒有定義的簡單函數:

class Bar: 

    def __init__(self): 
     pass 

    def foo(self): 
     try: 
      self._foo(self) 
     except AttributeError: 
      raise NotImplementedError 

    def set_foo(self, function): 
     setattr(self, '_foo', function) 

    def another_method(self): 
     print "Another method from {}".format(self) 


def foo(self): 
    self.another_method() 

bar = Bar() 
bar.set_foo(foo) 

bar.foo() 

所以,def foo(self)定義一個函數與一個參數self,等的方法。這個函數調用實例方法another_method

Bar.set_fooBar的實例中創建一個新屬性_foo

最後,Bar.foo試圖以self作爲參數訪問self._foo。如果_foo是不存在的,Bar.foo將引發一個NotImplementedError預期。

喜歡它,你可以從foo訪問self無子類。