相关疑难解决方法(0)

将方法添加到现有对象实例

我已经读过可以在Python中向现有对象(即,不在类定义中)添加方法.

我知道这样做并不总是好事.但是人们怎么可能这样做呢?

python oop methods monkeypatching

596
推荐指数
13
解决办法
22万
查看次数

Python:在运行时更改方法和属性

我希望在Python中创建一个可以添加和删除属性和方法的类.我该怎么做呢?

哦,请不要问为什么.

python reflection runtime

72
推荐指数
5
解决办法
6万
查看次数

在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.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)
Run Code Online (Sandbox Code Playgroud)

让我讨厌的是,键入函数的名称,instance_funcclass_func两次.

有没有简单的方法将现有函数添加到类或实例而不再键入函数的名称?

例如, A.add_function_as_bound_method(f)由于函数已经具有__name__属性,因此将现有函数添加到实例或类将是非常优雅的方式.

python

17
推荐指数
1
解决办法
5861
查看次数

标签 统计

python ×3

methods ×1

monkeypatching ×1

oop ×1

reflection ×1

runtime ×1