python - 如何检查对象属性是否属于方法包装器类型?

标签 python metaprogramming

一些 callable()对象的属性类型为 <class 'method-wrapper'> .是否可以检查可调用对象的类型是否为 method-wrapper

例如isinstance(object, methodwrapper)还是类似的东西?


基本上我想要实现的是:我有一个对象 a类型 A我想序列化它,以便我可以通过网络发送它。我还想“序列化”该对象的方法。特别是,我想通过网络发送每个方法的源代码,以便它可以在另一端的某个范围内执行并注入(inject)到 a 的重新创建中。因为方法可能已经更改或更新等。所以我遍历所有方法,一次“序列化”它们,然后发送 attribute_name -> attribute 的 json 字典。通过电线。但我不想尝试序列化 method-wrapper 类型的方法.现在一种方法就是在尝试序列化 method-wrappers 时 try catch 异常但我想知道是否还有其他方法。

最佳答案

既可行又不推荐。

'method-wrapper' 是一种实现类型,因此特定于 cPython。

Python 2.7.5+ (default, Sep 19 2013, 13:49:51) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> object().__str__
<method-wrapper '__str__' of object object at 0xb74dd4d0>
>>> type(object().__str__)
<type 'method-wrapper'>

好吧,但是...

Python 2.7.3 (2.0.2+dfsg-4, Jun 28 2013, 11:25:07)
[PyPy 2.0.2 with GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: ``"that's however just engineering"
(fijal)''
>>>> object().__str__
<bound method object.__str__ of <object object at 0xb6bd29e8>>
>>>> type(object().__str__)
<type 'method'>

因此,为了强调这种类型检查的想法有多不好,请看一些示例代码:

class T(object):
    def __init__(self, val):
        self.val = val
    def thing(self):
        pass

我在 cPython 中执行以下操作:

>>> isinstance(T(1).thing,type(object().__str__))
False

现在在 pypy 中:

>>>> isinstance(T(1).thing,type(object().__str__))
True

所以。如果您提供了有关您要完成的工作的更多详细信息,那可能会有所帮助。否则,我会给您留下上述警示故事。

关于python - 如何检查对象属性是否属于方法包装器类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19900354/

相关文章:

Python在成员函数中调用构造函数

c++ - 有什么方法可以从 C++ 中的成员指针类型派生对象类型

grails - 如何在Grails项目中包含Groovy

python - 如何获取某个.py文件中定义的所有函数?

c++ - 我如何获得一个模板来支持 T* 而不是 T&?

python - Gtk-警告 ** : cannot open display:

python - 格式化 Pandas 数据框中的时间戳

ruby - 如何使用 Groovy 将字段动态添加到 Java 类?

python - TypeError:labels不是numpy数组,也不是标量

python - 为什么 len(None) 不返回 0?