In this exercise, I’m asked to:
- define a class Circle with a method for calculating the area
- instantiate an object “circle” of class “Circle”
- define various variables pizza_area, table_area, etc. with the object “circle” to call the method “area”.
What I find confusing here is why you would instantiate a single circle and then use it to call the area method in each case instead of instantiating a circle class for the pizza, the table, and the room, and then calling the method for each. I suppose either way you would get the same result but it looks strange. What does it mean to create an object “circle” if it’s going to not remain constant?
class Circle:
pi = 3.14
def area(self, radius):
return self.pi * radius ** 2
circle = Circle()
pizza_area = circle.area(12/2)
teaching_table_area = circle.area(36/2)
round_room_area = circle.area(11460/2)
print(pizza_area)
1 Like
I agree it doesn’t add up. Consider static methods instead, they are made exactly for this purpose:
The @
signifies we are using a decorator pattern. You can think of it as imbuing the function with special properties, in this case the properties of a static method.
Why does it not take self as an argument? self
refers to particular instances of the class, which a static method call would have logical access to since it is accessed irrespective of instantiation. But then we can’t refer to self.pi
(since no self) or pi
(because of scope). That’s ok, the way you wrote it, pi
is already a static variable of the class and is available through Circle.pi
.
class Circle:
pi = 3.14
#notice we don't actually have access to self here, since we're not instantiating a unique instance
@staticmethod
def area(radius):
return Circle.pi * radius ** 2
#no need to instatiate
pizza_area = Circle.area(12/2)
teaching_table_area = Circle.area(36/2)
round_room_area = Circle.area(11460/2)
print(pizza_area)
If anyone that can recommend this to the CC team is reading, make note of this. Simply changing the example to a better use case is enough, or adding this as extra challenge for the curious.
1 Like
Frankly, you are entirely correct. The point of a class is to wrap state with the methods that leverage that state. In the example, pi
is constant, not state.
This would be preferable.
class Circle:
PI = 3.14
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.PI * self.radius ** 2
pizza_area = Circle(12/2).area()
print(pizza_area)
Then circle could have numerous methods that use that state, radius
.
1 Like