【发布时间】:2014-11-28 06:25:49
【问题描述】:
我想用新的属性和方法扩展一个对象,但是在运行时。基本上我宁愿只继承和扩展一个类,但基类的新对象通常不是使用它的构造函数创建的,而是使用相当复杂的函数。
而不是...
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 的行。
【问题讨论】:
-
Python 类定义都是在运行时执行的,所以 Python 中的继承已经是动态的。但是,您正在处理来自 C 扩展的函数和对象,可能不支持您正在尝试执行的操作。
标签: python inheritance python-3.x dynamic com