Classes

Hi,

I am working on classes and was wondering whether this code is valid? Could you please advise?

Original code:

class DistanceConverter:
  kms_in_a_mile = 1.609
  def how_many_kms(self, miles):
    return miles * self.kms_in_a_mile
converter = DistanceConverter() #instantiation and creating an object
kms_in_5_miles = converter.how_many_kms(5)
print(kms_in_5_miles)

Modified code:

class DistanceConverter:
  def __init__(self, miles):
    kms_to_mile = 1.609
    print (miles * kms_to_mile)
km_5_miles = DistanceConverter(5)

So adding init removed some steps and made it easier to call the class as a function?

Am I correct?

Thanks,
Abdalla

Classes seem like overkill here. I don’t like either to be honest, a simple function would the trick

the advantage of the original code is that we can easily call the method multiple times:

kms_in_10_miles = converter.how_many_kms(10)
kms_in_21_miles = converter.how_many_kms(21)
kms_in_42_miles = converter.how_many_kms(42)
2 Likes

Thanks for your reply, this code is in (class) lesson. It is just for practice.

1 Like

true, you have to start simple with classes. Making things too complex might overwhelm.

1 Like