Why is class variable referred to with self prefix instead of Class prefix? (within an instance method)

class DistanceConverter:
  kms_in_a_mile = 1.609
  def how_many_kms(self, miles):
    return miles * self.kms_in_a_mile   # reference to class variable prefixed with self
converter = DistanceConverter()
kms_in_5_miles = converter.how_many_kms(5) 


Why do we use self.kms_in_a_mile in this case instead of referring to Class.variable directly like DistanceConverter.kms_in_a_mile ?

I know using self.kms_in_a_mile would allow you to change the value at the instance level only, but isn’t the point of a class variable that all instance will share the same value?

Its confusing why its referred to as self.kms_in_a_mile


Technically, you can do either in this case. The output is the same whether you use DistanceConverter.kms_in_a_mile OR self.kms_in_a_mile.

Based on my current understanding, as I am learning along with you on this topic, I believe it is just the preferred practice.

Using self.var, whether it is a class or instance level variable, just makes it simpler. Either way, the variable belongs to the instance(self). A class variable, just happens to be the same among all instances of that class.

The class itself is just a template and does not actually make use of the variables until it is used to instantiate a specific instance of itself.

Kind Regards :slight_smile: