2014-03-28 30 views
0

我需要從SUDS模塊擴展類Client ...比如我有這個簡單的代碼工作正常如何在Python中正確地擴展類以及使用父類?

client = Client(wsdl, username = USERNAME, password = PASSWORD, headers = {'Content-Type': 'application/soap+xml'}, plugins = [VapixHelper()]) 

rules = client.service.GetActionRules() 

,所以我需要添加該類一些額外的方法,所以我儘量去做像這樣:

class Vapix(Client): 
    def __init__(self, args): 
     globals().update(vars(args)) 
     USERNAME, PASSWORD = user_data.split(':') 
     super(Vapix, self).__init__(wsdl, username = USERNAME, password = PASSWORD, headers = {'Content-Type': 'application/soap+xml'}, plugins = [VapixHelper()]) 

    def setActionStatus(self, status): 
     print super(Vapix, self).service.GetActionRules() 

,我得到這個錯誤,而不是結果:

Traceback (most recent call last): 
    File "vapix.py", line 42, in <module> 
    client.setActionStatus(True) 
    File "vapix.py", line 36, in setActionStatus 
    print super(Vapix, self).service.GetActionRules() 
AttributeError: 'super' object has no attribute 'service' 
+3

只需使用'self.service'。 – BrenBarn

+0

@BrenBarn很好的一個,謝謝...可能你可以提供一些信息,當需要調用父類時,'super(Vapix,self)'和'self'之間的區別在哪裏? – Kin

+1

你可能想要閱讀http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods – icedtrees

回答

2

你是不是覆蓋一個service()方法,所以你不需要使用super()找到一個原始的方法;除去super()呼叫,直接self訪問屬性來代替:

def setActionStatus(self, status): 
    print self.service.GetActionRules() 

super()時才需要,如果你需要搜索的基類(在方法解析順序,MRO)的方法(或其他描述對象)通常是因爲當前類已經重新定義了這個名字。

如果需要調用基類foo但目前該類實現foo方法,那麼你就不能使用self.foo(),你需要使用super()代替。你使用super()__init__例如;你的派生類都有自己的__init__方法,因此調用self.__init__()將遞歸調用相同的方法,但super(Vapix, self).__init__()作品,因爲super()着眼於self的MRO,在訂貨發現Vapix,然後去尋找一個具有__init__方法隔壁班的。

這裏service實例屬性;它直接在self上定義,甚至不是一種方法。

+0

是的,已經明白了這一點......你的回答中的一件事......如果我想要重寫父方法,我該怎麼辦? – Kin

+1

@Kirix:*然後*您將該方法命名爲相同,並使用'super()'調用父方法。 –