I am new to Python (usually work on C#), started using it over the last couple of days.
Within a class, do you need to prefix any call to that classes data members and methods? So, if I am calling a method or obtaining a value from that class, from within that class, I need to use self.method()
or self.intvalue
, for example?
I just want to check that there isn't a less verbose way that I have not encountered yet.
The self keyword is used to represent an instance (object) of the given class. In this case, the two Cat objects cat1 and cat2 have their own name and age attributes.
Use self when:you define an instance method, since it is passed automatically as the first parameter when the method is called; you reference a class or an instance attribute from inside an instance method; you want to refer to instance variables and methods from other instance methods.
self is only a reference to the current instance within the method. You can't change your instance by setting self .
There is no less verbose way. Always use self.x
to access the instance attribute x
. Note that unlike this
in C++, self
is not a keyword, though. You could give the first parameter of your method any name you want, but you are strongly advised to stick to the convention of calling it self
.
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