'self' in Python

The self in Python represents the instance of the class. Unlike this in C++, "self" is not a keyword , it's only a coding convention . Often, the first argument of a method is called self. 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. It binds the attributes with the given arguments. The use of self makes it easier to distinguish between instance attributes (and methods) from local variables.

You could declare variables within a class without using the self reference , but then those variables would be shared by all instances of that class, which may not be what you intended. In the example above, self.age = age and = name are declaring "instance variables" (as opposed to "class variables"), the values of which would be unique to the instantiated objects of that class. Otherwise, all students would have the same name and age.
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About