class Circle:
pi = 3.14
def area(self, radius):
area = 3.14 * radius ** 2
return area
circle = Circle()
pizza_area = circle.area(6)
print(pizza_area)
gives me the area.
but
class Circle:
pi = 3.14
def area(self, radius):
area = 3.14 * radius ** 2
return area
circle = Circle()
pizza_area = Circle.area(6)
print(pizza_area)
gives me an error. I’m not sure why? What’s the breakdown here? circle.area takes the circle variable and uses that as the self argument? Why doesn’t using Circle work?
I’ve edited your post for clarity, since you neglected to correctly format your code. Given that indentation is critical in Python, you might want to read up on how to correctly format your code for posting on the forums so that people can more easily help you in future.
The difference is that in your first example you are attempting to call an instance method, whereas in your second example you are attempting to call the same method as a class method. Since the method is not defined as a class method, what you’re doing will not work and hence you receive an error - which, incidentally, tells you what’s wrong:
Traceback (most recent call last):
File "<stdin>", line 9
pizza_area = Circle.area(6)
TypeError: area() missing 1 required positional argument: 'radius'
Your .area()
method requires two arguments. Ordinarily, when you have created an instance of your class, Python will supply self
for you and this refers back to the instance of the class, providing the mechanism by which you can change the state of the instance - changing the value of class attributes, for example.
When you attempt to do Circle.area(6)
, you’re effectively passing the integer value of 6
into the method as the self
argument. There is no value for radius
provided, which Python expects to find as an attribute in the second position, hence your error.
If you want to read more about the different ways that you can define methods on a Python class, then this article from Real Python is quite instructive.
If you simply want to know how to call a method from a class without creating an instance of the class first… well, think about what you might have to pass in to satisfy the self
argument as well as the area.
Have you figured it out?
I hope you at least had a go yourself!
Circle.area(Circle, 6)
>>> 113.04