Quantcast
Channel: What is the purpose of the `self` parameter? Why is it needed? - Stack Overflow
Viewing all articles
Browse latest Browse all 77

What is the purpose of the `self` parameter? Why is it needed?

$
0
0

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?.


Viewing all articles
Browse latest Browse all 77

Trending Articles