【问题标题】:How to add a method to a class from another file? [duplicate]如何从另一个文件向类添加方法? [复制]
【发布时间】:2021-10-22 09:16:36
【问题描述】:

如何在 python 中从另一个文件向类添加方法? 例如,我在文件main.py 中有类main,在文件method.py 中有函数something。我怎样才能使main 类具有函数something 作为方法?

【问题讨论】:

  • 在 main.py 中,from method import something。蟒蛇imports
  • 是的,但不会将函数添加为“main”类的方法
  • 我不需要派生类,只需要一个添加到不在定义函数的文件中的类的方法(那是因为我的代码会很长)
  • 感谢您的回答

标签: python function class methods


【解决方案1】:

您可以通过将函数分配给类的成员名称来完成猴子补丁:

class Main:
    def existing(self): print(f"existing in {type(self)}")

# monkey patch (can be in another file)
def something(self): print(f"something in {type(self)}")
Main.something = something


aMain = Main()

aMain.existing()
aMain.something()

existing in <class '__main__.Main'>
something in <class '__main__.Main'>

这也适用于子类:

class Sub(Main):
    def other(self): print(f"other in  {type(self)}")

aSub  = Sub()
aSub.existing()
aSub.other()
aSub.something()

existing in <class '__main__.Sub'>
other in  <class '__main__.Sub'>
something in <class '__main__.Sub'>

【讨论】:

    【解决方案2】:

    您需要动态添加它(这里是所有数据都在同一个文件中的示例)

    def function(p): return p
    
    class A:
       def __init__(self): pass
    
    # add as instance method
    setattr(A, 'function', lambda  self, p: function(p))
    # add as class method
    setattr(A, 'function_cls', classmethod(lambda cls, p: function(p)))
    # # add as static method
    setattr(A, 'function_static', staticmethod(lambda p: function(p)))
    
    print(a.function('p'))
    print(a.function.__class__)
    
    print(A.function_cls('p'))
    print(A.function_cls.__class__)
    
    print(A.function_static('p'))
    print(A.function_static.__class__)
    

    输出

    p
    <class 'method'>
    p
    <class 'method'>
    p
    <class 'function'>
    

    区别在于类和静态方法也可以像从类调用一样从实例调用

    【讨论】:

    • 感谢您的回答:)
    • 也可以通过改变setattr的字符串参数来改变它的名字
    • 如果我应该做一些需要自我参数的函数?比如它是否应该返回 self.dosomething()?
    • self 是将函数转换为方法所必须付出的代价,它携带实例的信息。尝试删除它...你会得到一个错误!
    • 所以我只能这样使用静态方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2015-04-19
    • 1970-01-01
    相关资源
    最近更新 更多