Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Using __self__ instead of self as first argument of "instance method"

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading