Python如何知道类中的变量是方法还是变量?

2024-04-18 15:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

print(hasattr(int,         '__call__'))
print(hasattr(lambda x: x, '__call__'))
print('')

class A(object):
    a = int
    b = lambda x : x

print(A.a)
print(A.b)

结果

True
True

<type 'int'>
<unbound method A.<lambda>>

Python如何决定什么将成为一个方法(这里是A.b)和什么将成为它自己(这里是A.a)?你知道吗


Tags: 方法lambdatrueobjecttypecallmethodclass
1条回答
网友
1楼 · 发布于 2024-04-18 15:30:19

如果对象是函数(也就是说,它们的类型是types.FunctionType),那么它们就被包装到方法中。你知道吗

这是因为函数类型定义了一个__get__方法,实现了descriptor protocol,它改变了查找A.b时发生的情况。int和大多数其他非函数可调用函数不定义此方法:

>>> (lambda x: x).__get__
<method-wrapper '__get__' of function object at 0x0000000003710198>
>>> int.__get__
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    int.__get__
AttributeError: type object 'int' has no attribute '__get__'

您可以通过定义其他类型的描述符来创建自己的类似方法包装器的行为。一个例子就是propertyproperty是一种类型,它不是函数,但也定义了__get__(和__set__)来更改查找属性时发生的情况。你知道吗

相关问题 更多 >