简体   繁体   English

在python中将方法添加到现有对象的任何优雅方法?

[英]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_funcclass_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.

相关问题 是否有任何优雅的方法将对象推入python元组前面? - Is there any elegant way to push an object into front of python tuple? Python:为方法调用添加可选参数的更优雅方式 - Python: More elegant way to add optional parameters to method call 在 Python 中获取相对路径的任何优雅方法? - Any elegant way to get relative path in Python? 在python中,有什么优雅的方法可以在类声明范围内引用类方法? - In python, any elegant way to refer to class method within the classes declaration scope? 有没有惯用的方法在Python中向对象添加方法? - Is there any idiomatic way to add methods to object in Python? 什么是处理python中不存在的属性的最优雅方法? - What is the most elegant way to handle non-existing attribute in python? Python 类:如何向现有对象(pandas 数据框)添加自定义方法 - Python Classes : How to add a custom method to an existing object (pandas dataframe) Python - 确定集合中是否存在任何对象的优雅方法 - Python - Elegant method of determining whether any objects exist in a collection 有没有优雅的方法在python中构建一个多级字典? - Is there any elegant way to build a multi-level dictionary in python? 优雅的方式来处理python类/方法命名上的冗余单词 - Elegant way to deal with redundant words on python class/method naming
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM