一些 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/