在 Python 3 中获取未绑定方法对象的定义类 [英] Get defining class of unbound method object in Python 3

查看:46
本文介绍了在 Python 3 中获取未绑定方法对象的定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想为类中定义的方法制作一个装饰器.我希望该装饰器在调用时能够在定义该方法的类上设置一个属性(以便将其注册到用于特定目的的方法列表中).

在 Python 2 中,im_class 方法很好地实现了这一点:

def 装饰器(方法):cls = method.im_classcls.foo = 'bar'返回方法

然而,在 Python 3 中,似乎不存在这样的属性(或它的替代品).我想这个想法是你可以调用 type(method.__self__) 来获取类,但这不适用于未绑定的方法,因为 __self__ == None 在那案例.

注意:这个问题实际上与我的情况有点无关,因为我选择在方法本身上设置一个属性,然后让实例扫描其所有方法寻找该属性在适当的时候.我(目前)也在使用 Python 2.6.但是,我很好奇是否有任何替代版本 2 的功能,如果没有,完全删除它的理由是什么.

编辑:我刚刚发现 这个问题.这使得看起来最好的解决方案就是像我一样避免它.我仍然想知道为什么它被删除了.

解决方案

您似乎缺少的一点是,在 Python 3 中,未绑定方法"类型已经完全消失——一个方法,直到并且除非它被绑定,否则是只是一个函数,没有用于执行的奇怪的类型检查"未绑定方法.这使语言更简单!

也就是说...:

<预><代码>>>>X级:... def Y(self): 通过...>>>类型(X.Y)<类'函数'>

瞧——一个不太需要担心的微妙概念和区别.这种简化是 Python 3 与 Python 2 相比的核心优势,它(多年来)积累了如此多的微妙之处,以至于它面临着真正失去其作为简单的地位的危险(如果不断添加功能) 语言.使用 Python 3,简单性回归!-)

Say I want to make a decorator for methods defined in a class. I want that decorator, when invoked, to be able to set an attribute on the class defining the method (in order to register it in a list of methods that serve a particular purpose).

In Python 2, the im_class method accomplishes this nicely:

def decorator(method):
  cls = method.im_class
  cls.foo = 'bar'
  return method

However, in Python 3, no such attribute (or a replacement for it) seems to exist. I suppose the idea was that you could call type(method.__self__) to get the class, but this does not work for unbound methods, since __self__ == None in that case.

NOTE: This question is actually a bit irrelevant for my case, since I've chosen instead to set an attribute on the method itself and then have the instance scan through all of its methods looking for that attribute at the appropriate time. I am also (currently) using Python 2.6. However, I am curious if there is any replacement for the version 2 functionality, and if not, what the rationale was for removing it completely.

EDIT: I just found this question. This makes it seem like the best solution is just to avoid it like I have. I'm still wondering why it was removed though.

解决方案

The point you appear to be missing is, in Python 3 the "unbound method" type has entirely disappeared -- a method, until and unless it's bound, is just a function, without the weird "type-checking" unbound methods used to perform. This makes the language simpler!

To wit...:

>>> class X:
...   def Y(self): pass
... 
>>> type(X.Y)
<class 'function'>

and voila -- one less subtle concept and distinction to worry about. Such simplifications are the core advantage of Python 3 wrt Python 2, which (over the years) had been accumulating so many subtleties that it was in danger (if features kept being added to it) of really losing its status as a simple language. With Python 3, simplicity is back!-)

这篇关于在 Python 3 中获取未绑定方法对象的定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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