2014-10-03 20 views
0

我想用新的屬性和方法擴展對象,但在運行時。基本上我寧願繼承和擴展一個類,但基類的新對象通常不是使用它的構造函數創建的,而是使用相當複雜的函數。使用繼承在運行時擴展Python對象

而不是...

from win32com import client 

excel = client.Dispatch("Excel.Application") 
excel.Visible = 1 
excel.Workbooks.Add() 
print(excel.Range("A1").value) 

...我需要這樣的東西(顯然打破):

from win32com import client 

class Excel(client.CDispatch): 
    def __init__(self): 
     self = client.Dispatch("Excel.Application") 

    def get(self, cell): 
     return self.Range(cell).value 

    def show(self): 
     self.Visible = 1 

excel = Excel() 
excel.show() 
excel.Workbooks.Add() # I want this to be still working 
print(excel.get("A1")) 

我還是希望能夠使用原來的方法和屬性 ,但也是我的新的。我無法理解這個概念,我甚至不知道如何調用這個原則。有任何想法嗎?

另一種方式來獲得所需的功能是這樣的:

from win32com import client 

class Excel(): 
    def __init__(self): 
     self.excel = client.Dispatch("Excel.Application") 
     self.Workbooks = self.excel.Workbooks 
     # I do not really want to repeat all base class 
     # functionality here to bind it to my new class 

    def get(self, cell): 
     return self.excel.Range(cell).value 

    def show(self): 
     self.excel.Visible = 1 

excel = Excel() 
excel.show() 
excel.Workbooks.Add() 
print(excel.get("A1")) 

這一工程,但需要我做了很多類似self.Workbooks = self.excel.Workbooks線。

+0

Python類定義在運行時都執行,所以繼承在Python *已經是動態*。但是,您正在處理來自C擴展的函數和對象,這可能不支持您正在嘗試執行的操作。 – 2014-10-03 07:24:52

回答

3

實現繼承主要是組合/委託模式的變體。好消息是Python使委派非常容易。我還沒有嘗試(不工作在Windows上),但下面的代碼片段可能只是工作:

from win32com import client 

class Excel(object): 
    def __init__(self): 
     self._app = client.Dispatch("Excel.Application") 

    def get(self, cell): 
     return self._app.Range(cell).value 

    def show(self): 
     self._app.Visible = 1 

    def __getattr__(self, name): 
     try: 
      return getattr(self._app, name) 
     except AttributeError: 
      raise AttributeError(
       "'%s' object has no attribute '%s'" % (type(self).__name__, name)) 
+0

正是我需要的。謝謝! – Fenikso 2014-10-03 07:37:36