0

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
1
  • Add self as first argument to area method Commented May 10, 2022 at 16:12

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.