简体   繁体   English

类绑定函数python 2和3

[英]Class bound function python 2 and 3

In python 2 I could create a class bound method using: 在python 2中,我可以使用以下方法创建类绑定方法:

types.MethodType(func, None, cls)

However in python3 MethodType does not take the 3rd parameter. 但是在python3中,MethodType不采用第3个参数。

How can I achieve the same behaviour in python 3? 如何在python 3中实现相同的行为? Preferably in a way that is still valid in python2.7. 最好以在python2.7中仍然有效的方式。

It seems that in Python3, you don't need to use MethodType anymore to create class bound methods (though you still need it to assign instance bound methods). 似乎在Python3中,您不再需要使用MethodType来创建类绑定的方法(尽管您仍然需要它来分配实例绑定的方法)。 Thus if you're going to do this: 因此,如果要执行此操作:

class A:
  def __init__(self):
    pass
# end of class definition
# ...
# whoops I forgot a method for A
def foo(self, *args):
  pass

You can later attach foo to A using just A.foo = foo . 您以后可以仅使用A.foo = foofoo附加到A (In Python2 you had to use A.foo = types.MethodType(foo, None, A) or such.) (在Python2中,您必须使用A.foo = types.MethodType(foo, None, A)等。)

If you want to add foo just to a particular instance of A , you would still use MethodType , although (in Python3) only with two arguments: 如果要将foo仅添加到A的特定实例,则仍将使用MethodType ,尽管(在Python3中)仅具有两个参数:

a = A()
a.foo = types.MethodType(foo, a)

(In Python2, you had to use a.foo = types.MethodType(foo, a, A) or such.) (在Python2中,您必须使用a.foo = types.MethodType(foo, a, A)等。)

As far as I can see, if you want a strategy that works with both versions, you'd have to do something like this: 据我所知,如果您想同时使用两个版本的策略,则必须执行以下操作:

try:
  A.foo = types.MethodType(foo, None, A)
except TypeError:
  # too many arguments to MethodType, we must be in Python3
  A.foo = foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM