I recently came across this piece of code:
class InlineParameterResolver:
def resolve(__self__, value: str) -> Any:
return value
Now, I am aware that this code is strange as the class itself has no instance methods, nor an init method to enable it to create an instance and operate on its internal attributes, but does having the __self__ as the first argument have any special function/behaviour?
I have tried to google for an answer, but couldn’t find anything, I just want to know if this is an opportunity to learn something, or if I’m just reading Python from someone who didn’t have a lot of experience with the language.
Cheers.
>Solution :
does having the
__self__as the first argument have any special function/behaviour?
There is no special function or behavior. Even using self is just a naming convention for the first positional argument, using foo or anything else would work all the same.
However, using the name __self__ is not advisable, because that already has a different meaning in the datamodel: when an instance method object is created by retrieving a function object from a class via one of its instances, its __self__ attribute is the instance, and the method object is said to be bound.
>>> class A:
... def f(self):
... pass
...
>>> a = A()
>>> a.f.__self__
<__main__.A object at 0xdeadbeef>
Using double underscore names as function arguments is strange enough to cause confusion, so I’d recommend avoiding that.