Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 'self' keyword

Tags:

python

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.

like image 928
Darren Young Avatar asked May 16 '11 15:05

Darren Young


People also ask

What is the self keyword in Python?

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.

Where do we use self in Python?

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.

Can you set self in Python?

self is only a reference to the current instance within the method. You can't change your instance by setting self .


1 Answers

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.

like image 108
Sven Marnach Avatar answered Sep 18 '22 00:09

Sven Marnach