[英]Any elegant way to add a method to an existing object in python?
After a lot of searching, I have found that there are a few ways to add an bound method or unbound class methods to an existing instance objects 经过大量搜索,我发现有几种方法可以将绑定方法或未绑定类方法添加到现有实例对象
Such ways include approaches the code below is taking. 这些方式包括以下代码采用的方法。
import types
class A(object):
pass
def instance_func(self):
print 'hi'
def class_func(self):
print 'hi'
a = A()
# add bound methods to an instance using type.MethodType
a.instance_func = types.MethodType(instance_func, a) # using attribute
a.__dict__['instance_func'] = types.MethodType(instance_func, a) # using __dict__
# add bound methods to an class
A.instance_func = instance_func
A.__dict__['instance_func'] = instance_func
# add class methods to an class
A.class_func = classmethod(class_func)
A.__dict__['class_func'] = classmethod(class_func)
What makes me annoying is, typing the function's name, instance_func
or class_func
twice. 让我讨厌的是,输入函数的名称,
instance_func
或class_func
两次。
Is there any simple way to add an existing function to an class or instance without typing the function's name again? 有没有简单的方法将现有函数添加到类或实例而不再键入函数的名称?
For example, A.add_function_as_bound_method(f)
will be far much elegant way to add an existing function to an instance or class since the function already has __name__
attribute. 例如,
A.add_function_as_bound_method(f)
将是一个非常优雅的方式将现有函数添加到实例或类,因为该函数已具有__name__
属性。
Normally, functions stored in object dictionaries don't automatically turn into boundmethods when you look them up with dotted access. 通常,当您使用虚线访问查找时,存储在对象词典中的函数不会自动转换为bound方法。
That said, you can use functools.partial to pre-bind the function and store it in the object dictionary so it can be accessed like a method: 也就是说,您可以使用functools.partial预绑定函数并将其存储在对象字典中,以便可以像方法一样访问它:
>>> from functools import partial
>>> class Dog:
def __init__(self, name):
self.name = name
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> def bark(self): # normal function
print('Woof! %s is barking' % self.name)
>>> e.bark = partial(bark, e) # pre-bound and stored in the instance
>>> e.bark() # access like a normal method
Woof! Buddy is barking
This is a somewhat elegant way to add a method to an existing object (without needing to change its class and without affecting other existing objects). 这是一种向现有对象添加方法的一种稍微优雅的方式(无需更改其类并且不影响其他现有对象)。
Follow-up to Comment: 评论后续行动:
You can use a helper function to add the pre-bound function is a single step: 您可以使用辅助函数添加预绑定函数是一个步骤:
>>> def add_method(obj, func):
'Bind a function and store it in an object'
setattr(obj, func.__name__, partial(func, obj))
Use it like this: 像这样使用它:
>>> add_method(e, bark)
>>> e.bark()
Woof! Fido is barking
Hope this is exactly what you need :-) 希望这正是你所需要的:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.