Quantcast
Viewing latest article 7
Browse Latest Browse All 77

Answer by prosti for What is the purpose of the `self` parameter? Why is it needed?

self is inevitable.

There was just a question should self be implicit or explicit.Guido van Rossum resolved this question saying self has to stay.

So where the self live?

If we would just stick to functional programming we would not need self.Once we enter the Python OOP we find self there.

Here is the typical use case class C with the method m1

class C:    def m1(self, arg):        print(self, ' inside')        passci =C()print(ci, ' outside')ci.m1(None)print(hex(id(ci))) # hex memory address

This program will output:

<__main__.C object at 0x000002B9D79C6CC0>  outside<__main__.C object at 0x000002B9D79C6CC0>  inside0x2b9d79c6cc0

So self holds the memory address of the class instance.The purpose of self would be to hold the reference for instance methods and for us to have explicit access to that reference.


Note there are three different types of class methods:

  • static methods (read: functions),
  • class methods,
  • instance methods (mentioned).

Viewing latest article 7
Browse Latest Browse All 77

Trending Articles