Using self
is a design decision by python, not strictly mandatory from a language design point of view, to make explicit the instance object and distinguish instance variables from local variables. You could conceive of an alternative where self
is always implicitly there, as Guido's blogpost responds to:
class MyClass: def __init__(n): # implicit self self.n = n def print_n(): print(self.n)
This goes against python's mantra of "explicit is better than implicit". Or use special syntax to refer to instance variables as in Ruby. However Python tries to keep syntax characters to a minimum (nowadays it is adding more syntax, like assignment expressions and type hinting). This is functionally the same as implicit self
, except you don't treat self
like a hidden variable.
class MyClass: def __init__(n): @n = n def print_n(): print(@n)
Another alternative is C++ style syntax, using implicit this
and explicit dataclass-like declarations (which are relatively new):
class MyClass: n: int def __init__(n): this.n = n def print_n(): print(n) # default to instance variable
this
is only used to disambiguate the local variable from the instance variable. If there is no confusion, the "class scope" n
is used. I think this is cleaner than using explicit self
everywhere, but you need to keep track of what is and isn't instance state.