在Python 3中检测类(不是实例)中的绑定方法 [英] Detecting bound method in classes (not instances) in Python 3

查看:183
本文介绍了在Python 3中检测类(不是实例)中的绑定方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个带有函数或方法 f 的类 C ,我使用 inspect。 ismethod(obj.f)(其中 obj C 的一个实例)如果 f 是绑定方法或不是。有没有办法直接在课堂上做同样的事情(不需要创建一个对象)?



inspect.ismethod不起作用:

  class C (object):

@staticmethod
def st(x):
pass

def me(self):
pass $ b (在Python 3中):
$ b obj = C()

/ p>

 >>> inspect.ismethod(C.st)
False
>>> inspect.ismethod(C.me)
False
>>> inspect.ismethod(obj.st)
False
>>> inspect.ismethod(obj.me)
True

我想我需要检查函数/方法是类的成员,而不是静态的,但我无法轻松完成。我想这可以使用 classify_class_attrs 来完成,如下所示
你将如何确定Python类的每个属性和方法的定义?
但我希望有另一种更直接的方式。

解决方案

Python 3中没有未绑定的方法,所以您无法检测到它们无论是。你所拥有的只是常规功能。您至多可以看到他们是否拥有限定名称,表示它们是嵌套,它们的第一个参数名称是 self :



<$在方法.__ qualname__和inspect.getargspec(方法).args [0] =='self':
#常规方法中,如果'。'为p $ p> *可能*

这当然不会完全适用于静态方法和嵌套函数, $ c> self 作为第一个参数,以及不使用 self 作为第一个参数的常规方法)。



对于静态方法和类方法,您必须查看类字典

 >>> isinstance(vars(C)['st'],staticmethod)
True

这是因为 C .__ dict __ ['st'] 是在 staticmethod docs.python.org/3/howto/descriptor.htmlrel =nofollow>绑定到类

Given a class C with a function or method f, I use inspect.ismethod(obj.f) (where obj is an instance of C) to find out if f is bound method or not. Is there a way to do the same directly at the class level (without creating an object)?

inspect.ismethod does not work as this:

class C(object):

    @staticmethod
    def st(x):
        pass

    def me(self):
        pass

obj = C()

results in this (in Python 3):

>>> inspect.ismethod(C.st) 
False
>>> inspect.ismethod(C.me)
False
>>> inspect.ismethod(obj.st) 
False
>>> inspect.ismethod(obj.me)
True

I guess I need to check if the function/method is member of a class and not static but I was not able to do it easily. I guess it could be done using classify_class_attrs as shown here How would you determine where each property and method of a Python class is defined? but I was hoping there was another more direct way.

解决方案

There are no unbound methods in Python 3, so you cannot detect them either. All you have is regular functions. At most you can see if they have a qualified name with a dot, indicating that they are nested, and their first argument name is self:

if '.' in method.__qualname__ and inspect.getargspec(method).args[0] == 'self':
    # regular method. *Probably*

This of course fails entirely for static methods and nested functions that happen to have self as a first argument, as well as regular methods that do not use self as a first argument (flying in the face of convention).

For static methods and class methods, you'd have to look at the class dictionary instead:

>>> isinstance(vars(C)['st'], staticmethod)
True

That's because C.__dict__['st'] is the actual staticmethod instance, before binding to the class.

这篇关于在Python 3中检测类(不是实例)中的绑定方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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