How does Python know if a variable in a 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)

leads to

True
True

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

How does Python decide what the method will be (like A.bhere) and what will only happen by itself (like A.ahere)?

+4
source share
1 answer

Things are wrapped in methods if they are functions (i.e. their type types.FunctionType).

This is because the type of function determines the method __get__that implements the descriptor protocol , which changes what happens when you look A.bup. intand most other non-functional calls do not define this method:

>>> (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 - , , a __get__ ( __set__), , .

+6

Source: https://habr.com/ru/post/1533840/


All Articles