does it mean, that __get__
acts differently based on whether it works on a non-callable vs a callable?
I have recently come across it, so I do not know about it in much detail, but from what I have seen,
def func(self):
return self
type(func)
gives,
function
class A:
pass
a = A()
when we do,
func = func.__get__(a, A)
func
now, our function is bound to the instance a
<bound method func of <__main__.A object at 0x7f0285a4eb90>>
here, the __get__
is probably not intuitive for what it does, and should be renamed to __bind__
the other functionality that I am aware of is,
class Descriptor:
def __set__(self, instance, value):
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
print(self, instance, owner, sep='\n')
return instance.__dict__[self.name]
def __set_name__(self, cls, name):
self.name = name
class B:
x = Descriptor()
b = B()
here, __get__
is used for accessing the x
attribute of instance b
.
b.x = 10
b.x
gives,
<__main__.Descriptor object at 0x7f0285a71ed0>
<__main__.B object at 0x7f0285a71310>
<class '__main__.B'>
10
here, __get__
is used for retrieving the value.
but how are these two functionalities related to each other, as they appear to be two completely different tasks achieved by the same __get__
.