通过在定义后添加更多方法来扩展python类

时间:2022-02-03 10:38:13
class A:
    pass

def b(self):
    print('b')

A.b = b

a = A()

At this point a.b is a bound method object which is great, but if i say:

此时a.b是一个很好的绑定方法对象,但如果我说:

a.b() 

I get an error saying that b needs at least one argument.

我得到一个错误,说b需要至少一个参数。

My questions are: 1. how does one go about tacking methods onto existing classes? and 2. are there any documented 'best practices' with regard to this sort of thing?

我的问题是:1。如何将方法引入现有类? 2.对于这类事情,是否有任何记录在案的“最佳实践”?

1 个解决方案

#1


1  

That should work fine (see: http://ideone.com/WWPg8)

这应该可以正常工作(参见:http://ideone.com/WWPg8)

Python functions are descriptors, and convert to unbound and bound methods when accessed on classes and instances respectively; see http://docs.python.org/howto/descriptor.html

Python函数是描述符,分别在类和实例*问时转换为未绑定和绑定的方法;见http://docs.python.org/howto/descriptor.html

"Monkey patching" classes and instances is considered perfectly OK, as long as you're clear about what you're doing and document it sufficiently.

“猴子修补”类和实例被认为是完全可以的,只要你清楚你正在做什么并充分记录它。

#1


1  

That should work fine (see: http://ideone.com/WWPg8)

这应该可以正常工作(参见:http://ideone.com/WWPg8)

Python functions are descriptors, and convert to unbound and bound methods when accessed on classes and instances respectively; see http://docs.python.org/howto/descriptor.html

Python函数是描述符,分别在类和实例*问时转换为未绑定和绑定的方法;见http://docs.python.org/howto/descriptor.html

"Monkey patching" classes and instances is considered perfectly OK, as long as you're clear about what you're doing and document it sufficiently.

“猴子修补”类和实例被认为是完全可以的,只要你清楚你正在做什么并充分记录它。