在另一个python类中使用未绑定的方法 [英] using unbound methods in another python class

查看:68
本文介绍了在另一个python类中使用未绑定的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与<unbound method foo.ops>一样的未绑定方法,我想在另一个类中使用相同的方法.举个例子

I have an unbound method as <unbound method foo.ops>, i would like to use the same method with another class. take an example

class foo2(object):
  pass

foo2.ops = foo.ops

但是

obj = foo2()
obj.ops()

raises TypeError: unbound method ops() must be called with foo instance as first argument (got nothing instead)

推荐答案

如果要将相同的方法添加到几个不相关的类中(例如,执行AOP),请不要从其中一个中复制未绑定的方法.而是定义一个普通函数并将其作为方法分配给每个类.

If you want to add the same method to several unrelated classes (e.g. doing AOP), don't copy an unbound method from one of them. Instead, define a plain function and assign it as a method to every class.

通常,更好的方法是mixin(使用纯继承)或元类(类装饰器语法简洁).

Usually a better way to do it is a mixin (using plain inheritance) or a metaclass (class decorator syntax is neat).

如果您很想从类中窃取某个方法(例如,您无法控制的方法),则可以从未绑定方法"包装器中提取该方法:foo2.ops.im_func;这是一个简单的函数,您可以将其作为方法分配给另一个类.

If you're hell-bound to steal a method from a class (e.g. one you don't control), you can extract it from the 'unbound method' wrapper: foo2.ops.im_func; it's a plain function and you can assign it as a method to another class.

这篇关于在另一个python类中使用未绑定的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆