'Python Argument TypeError

Can somebody tell me why I am getting error in it?

import math
class Weight():
    def area(r):
        return math.pi*r*r
obj=Weight()
r=int(input("Enter the radius of circle"))
print(obj.area(r))
TypeError: area() takes 1 positional argument but 2 were given


Solution 1:[1]

You forgot self:

import math
class Weight():
    def area(self, r):
        return math.pi*r*r
obj=Weight()
r=int(input("Enter the radius of circle"))
print(obj.area(r))

If you're writing a class, that is not actually needs to be instantiated, or writing a method, that does not actually need an instance, you can use @classmethod and @staticmethod decorators. The first one replaces an instance (self == Weight()) with the class itself (cls == Weight); the second one doesn't pass the first argument at all.

Below is the example of their use:

import math
class Weight:
    @staticmethod
    def area(r):
        return math.pi*r*r

    @classmethod
    def double_area(cls, r):
        return cls.area(r) * 2


r=int(input("Enter the radius of circle"))
print(Weight.area(r))
print(Weight.double_area(r))

Solution 2:[2]

Add self as first argument to area method as such:

import math
class Weight():
    def area(self, r):
        return math.pi*r*r
obj=Weight()
r=int(input("Enter the radius of circle"))
print(obj.area(r))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2