Are you supposed to use self
when referencing a member function in Python (within the same module)?
More generally, I was wondering when it is required to use self
, not just for methods but for variables as well.
You use self when: Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called. Referencing a class or instance attribute from inside an instance method.
Self is a convention and not a Python keyword . self is parameter in Instance Method and user can use another parameter name in place of it. But it is advisable to use self because it increases the readability of code, and it is also a good programming practice.
Use self
to refer to instance variables and methods from other instance methods. Also put self
as the first parameter in the definition of instance methods.
An example:
class MyClass(object): my_var = None def my_method(self, my_var): self.my_var = my_var self.my_other_method() def my_other_method(self): # do something...
Adding an answer because Oskarbi's isn't explicit.
You use self
when:
You don't use self
when
instance = MyClass()
, you call MyClass.my_method
as instance.my_method(some_var)
not as instance.my_method(self, some_var)
.These don'ts are just examples of when not to use self. The dos are when you should use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With