【问题标题】:Using setattr() to overload a method in an already existing class definition使用 setattr() 重载已经存在的类定义中的方法
【发布时间】:2020-05-09 12:08:13
【问题描述】:

我想知道是否可以向现有类添加方法,重载现有方法。我知道,我可以使用 setattr() 向类添加函数,但是重载不起作用。

作为一个例子,我想添加到类中

class foo:
    def hello(self):
        print("hello")

以下函数,重载“hello”

def hello2(self,baa):
    self.hello()
    print(str(baa))

很明显这是可行的

setattr(foo,"hello2",hello2)    
test = foo()
test.hello()
test.hello2("bye")

但我希望能够这样称呼它

test.hello("bye")

有没有可能的方法来做到这一点? 编辑:谢谢大家的回答!对我来说重要的是,我真的可以重载,而不仅仅是替换现有的方法。我改变了我的例子来反映这一点!

干杯!

【问题讨论】:

标签: python overloading


【解决方案1】:
class foo():
    def hello(self, baa=""):
        print("hello"+str(baa))


def main():
     test = foo()
     test.hello()
     test.hello("bye")

会输出

hello hellobye

【讨论】:

    【解决方案2】:

    您实际上可以避免在此处使用setattr。由于您提前知道要重载的方法,您可以这样做:

    def hello2(self, baa):
        print("hello"+str(baa))
    

    接着;

    foo.hello = hello2
    test = foo()
    test.hello()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-12
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多