【问题标题】:modify method only having the method's name and instance object修改方法只有方法的名称和实例对象
【发布时间】:2013-01-29 18:41:56
【问题描述】:

我知道getattr()可以调用该方法,但是我需要覆盖它,所以myInstance.mymethod会被覆盖。

我将方法的名称作为字符串和实例的引用。

【问题讨论】:

  • 你想用什么替换它
  • 另一个函数,还有什么?

标签: python class methods instance


【解决方案1】:

你可以用setattr覆盖它

>>> class Foo(object):
...    def method(self): pass
... 
>>> a = Foo()
>>> a.method()
>>> setattr(a,'method',1)
>>> a.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

用另一种方法替换:

>>> import types
>>> setattr(a,'method',types.MethodType(lambda self: self.__class__.__name__,a))
>>> a.method()
'Foo'

其中 lambda 东西只是定义函数的花哨的简写:

def func(self):
    return self.__class__.__name__

setattr(a,'method',types.MethodType(func,a))

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 2022-01-13
    • 2020-06-30
    相关资源
    最近更新 更多