Consider this example:
class MyClass:
def func(self, name):
self.name = name
I know that self
refers to the specific instance of MyClass
. But why must func
explicitly include self
as a parameter? Why do we need to use self
in the method's code? Some other languages make this implicit, or use special syntax instead.
For a language-agnostic consideration of the design decision, see What is the advantage of having this/self pointer mandatory explicit?.
To close debugging questions where OP omitted a self
parameter for a method and got a TypeError
, use TypeError: method() takes 1 positional argument but 2 were given instead. If OP omitted self.
in the body of the method and got a NameError
, consider How can I call a function within a class?.
@name
more intuitive thanself.name
? The latter, IMO, is more intuitive. – Eligaself
. You would call the method likegetUserType()
. If you needed another parameter, yes, you would need to define the method to take another parameter. – Adventurer