【问题标题】:Is it possible to define additional class methods in another module?是否可以在另一个模块中定义其他类方法?
【发布时间】:2021-09-21 21:13:53
【问题描述】:

我想知道这样的事情在 Python 中是否可行。假设在一个库中,有一个类X 定义了方法abc

class X:
  def a(self):
     ...
  def b(self):
     ...
  def c(self):
     ...

我想在类X 中添加一个方法custom(这样我就可以调用X().custom())而不修改库代码。

我知道我可以做类似的事情

def custom(self):
   ...
X.custom = custom

但是这样做看起来不太好。

有没有更智能的方法来实现我想要的(例如类似于 impl 上的 Rust 结构)?

【问题讨论】:

  • 为什么不子类化它并在那里添加方法?
  • 你可以继承它。
  • 没错,我可能只是过度劳累了。谢谢!

标签: python class methods


【解决方案1】:

如果您使用的是 python3,请导入库然后展开类,如下所述 - 假设父代码(编写 X 类的地方)在 main.py 中,那么我们可以这样做 -

import main

class X(main.X):

    def custom():
        print("hello hi")
        #your code

详情可以参考-How to extend a class in python?

【讨论】:

    猜你喜欢
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多