Methods can also take more arguments than just
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"
Above we defined a
DistanceConverter class, instantiated it, and used it to convert 5 miles into kilometers. Notice again that even though
how_many_kms takes two arguments in its definition, we only pass
self is implicitly passed (and refers to the object
It’s March 14th (known in some places as Pi day) at Jan van High, and you’re feeling awfully festive. You decide to create a program that calculates the area of a circle.
Circle class with class variable
pi to the approximation
area method that takes two parameters:
Return the area as given by this formula:
area = pi * radius ** 2
Create an instance of
Circle. Save it into the variable
You go to measure several circles you happen to find around.
- A medium pizza that is 12 inches across.
- Your teaching table which is 36 inches across.
- The Round Room auditorium, which is 11,460 inches across.
You save the areas of these three things into
Remember that the
radius of a circle is half the diameter. We gave three diameters here, so halve them before you calculate the given circle’s area.