Self.class_variable or ClassName.class_variable?


why in this lesson in the lesson part the class variable is preceded by self when used in return part (self.kms_in_a_mile), but in the exercise part it is preceded by the class name (Circle.pi), in the method part?

To be honest, when I was doing the exercise I just wrote the class variable name (pi) and only after receiving an error I fixed it, but the point is that I still don’t quite understand.

Thank you.

It’s a matter of preference. Both pi and kms_in_a_mile are (presumably) constants, and I’d prefer to call them using ClassName.class_obj.

If the attribute is going to be something unique to the object, use self.class_obj.

Be aware that once you change that value within an instance using self.class_obj, the new value will apply to the particular instance from then on. If you change it using Class.class_obj, it will be changed for every instance. You could, for example, do this in __init__() to keep a count of the number of instances of a class.

1 Like