[英]How does Python know whether a variable in the class is a method or a variable?
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如何決定什么是方法(如Ab
在這里)以及本身將會是什么(如Aa
在這里)?
如果它們是函數(即它們的類型是types.FunctionType
),事物就會被包裝到方法中。
這是因為函數類型定義了一個__get__
方法,實現了描述符協議 ,它改變了查找Ab
時發生的事情。 int
和大多數其他非函數callables不定義此方法:
>>> (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__'
您可以通過定義其他類型的描述符來創建自己的方法包裝器行為。 一個例子是property
。 property
是一個不是函數的類型,但是還定義了一個__get__
(和__set__
)來改變查找屬性時發生的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.