【发布时间】:2018-01-11 15:45:32
【问题描述】:
我查看了以下帖子和博客,这些帖子和博客解释了如何使用函数执行此操作。我想知道对类或对象方法做同样的事情是否合法? 将感谢适用于 Python2 的答案(尽管很高兴知道它如何适用于 Python3)。
来自stackoverflow的来源:
Override module method where from...import is used 和 Override a method at instance level
内容相似的博客:
https://tryolabs.com/blog/2013/07/05/run-time-method-patching-python/ http://igorsobreira.com/2011/02/06/adding-methods-dynamically-in-python.html
这段代码说明了我的意图和我的尝试:
class Person:
def __init__(self, name):
self.name = name
class OtherPerson:
def __init__(self, name):
self.name = name
def do_something(self):
print self.name + '$$'
p = Person('alpha')
p.do_something = OtherPerson.do_something
# TypeError: unbound method do_something() must be called with
OtherPerson #instance as first argument (got nothing instead)
p.do_something()
op = OtherPerson('beta')
p.do_something = op.do_something
# output: 'beta$$' I would like to get 'alpha$$'
p.do_something()
尝试了@khelwood 的以下建议:
Person.do_something = OtherPerson.do_something
#TypeError: unbound method do_something() must be called with OtherPerson instance as first argument (got nothing instead)
# Works if OtherPerson.do_something is staticmethod
p.do_something()
【问题讨论】:
-
你可以做
Person.do_something = OtherPerson.do_something,如果这是你的要求 -
我敢肯定,任何国家/地区的书籍都没有法律规定它非法...;)
-
@khelwood 感觉它会起作用,但不幸的是它不起作用。得到同样的错误:TypeError: unbound method do_something() must be called with OtherPerson instance as first argument (什么都没有代替)
-
那我猜你使用的是 Python 2。
-
@khelwood :正确,使 Person 和 OtherPerson 从对象扩展也无济于事。那么在 Python 2 中是 not allowed 而在 Python 3 中是 allowed 吗?这解决了我猜想的问题的法律部分! (在:deceze)
标签: python dynamic overriding