【问题标题】:Extend Python object in run-time using inheritance使用继承在运行时扩展 Python 对象
【发布时间】: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


【解决方案1】:

实现继承主要是组合/委托模式的变体。好消息是 Python 使委托变得非常容易。我没有尝试过(不在 Windows 上工作),但以下 sn-p 可能只是工作:

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))

【讨论】:

  • 正是我需要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 2011-03-03
  • 2017-05-18
  • 2012-08-27
  • 2022-01-11
  • 1970-01-01
相关资源
最近更新 更多