What did self do here? (Classes)

class DistanceConverter:
  kms_in_a_mile = 1.609
  def how_many_kms(self, miles):
    return miles * self.kms_in_a_mile

converter = DistanceConverter()
kms_in_5_miles = converter.how_many_kms(5)
print(kms_in_5_miles)
# prints "8.045"

In the method, we have two arguments and we returned the value of miles * kms_in_a_mile. I noticed that it doesn’t work(It says its not defined) if you removed self but I don’t understand why. kms_in_a_mile is defined already.

you can also do:

class DistanceConverter:
  kms_in_a_mile = 1.609
  def how_many_kms(self, miles):
    return miles * DistanceConverter.kms_in_a_mile

converter = DistanceConverter()
kms_in_5_miles = converter.how_many_kms(5)
print(kms_in_5_miles)
# prints "8.045"

kms_in_a_mile might be defined, but inside the class. Not in the global namespace, you would have to use class.class_property or self (the current class instance) to get the class property

2 Likes