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
CodePudding user response:
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))
CodePudding user response:
Add self as first argument to area method
