Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,有什么优雅的方法可以向现有对象添加方法吗?_Python - Fatal编程技术网

在python中,有什么优雅的方法可以向现有对象添加方法吗?

在python中,有什么优雅的方法可以向现有对象添加方法吗?,python,Python,经过大量搜索,我发现有几种方法可以将绑定方法或未绑定类方法添加到现有的实例对象中 这些方法包括下面代码所采用的方法 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.in

经过大量搜索,我发现有几种方法可以将绑定方法或未绑定类方法添加到现有的实例对象中

这些方法包括下面代码所采用的方法

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)
让我恼火的是,输入函数名,
instance\u func
class\u func
两次

有没有简单的方法可以将现有函数添加到类或实例中,而无需再次键入函数名

比如说,,
A.add\u function\u as\u bound\u method(f)
将现有函数添加到实例或类中是一种非常优雅的方式,因为该函数已经具有
\uuu name\uuuu
属性。

通常,当您使用点式访问查找对象字典中存储的函数时,它们不会自动变成boundmethods

也就是说,您可以使用预绑定函数并将其存储在对象字典中,以便像方法一样访问它:

>>> 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
这是一种向现有对象添加方法的优雅方式(无需更改其类,也不影响其他现有对象)

后续评论:

您可以使用助手函数添加预绑定函数,只需一步:

>>> def add_method(obj, func):
        'Bind a function and store it in an object'
        setattr(obj, func.__name__, partial(func, obj))
像这样使用它:

>>> add_method(e, bark)
>>> e.bark()
Woof! Fido is barking

希望这正是您所需要的:-)

假设将bark函数编码为字符串,是否可以在类初始化期间像中所问的那样执行相同的操作?