Home > database >  Power a number with input() and function within class
Power a number with input() and function within class

Time:08-18

I'm able to calculate area of square without using class/method but when I want to add it to the class if it is failing on line 8 with the following error:

area() takes 1 positional argument but 2 were given

My code try is:

class Square():
    def area(side_length):
        calc = side_length**2
        return calc

figure = Square()
side_length = int(input("Enter side length: "))
print(figure.area(side_length))

If I run this code, it works fine. I think I'm doing smth wrong in calling methods:

def area(side_length):
        calc = side_length**2
        return calc
side_length = int(input("Enter side length: "))
area(side_length)

CodePudding user response:

class Square():
    def area(self, side_length):
        calc = side_length**2
        return calc

figure = Square()
side_length = int(input("Enter side length: "))
print(figure.area(side_length))

please mind that in python, every instance method has at least one argument, for example there. when you call figure.area, you are passing two parameters to area method:

  1. figure object (that is always first parameter)
  2. side_length

so when you are defining an instance method, you must set a parameter for figure object even if you don't use it... It can have any name you want, but it is highly recommended to use self and it is a contract. self refers to figure

CodePudding user response:

you forgot self parameter

class Square():
def area(self, side_length):
    calc = side_length**2
    return calc

figure = Square()
side_length = int(input("Enter side length: "))
print(figure.area(side_length))

CodePudding user response:

All class methods (which are not decorated with @staticmethod or @classmethod) need a self parameter:

class Square:
    def area(self, side_length):
        calc = side_length ** 2
        return calc

figure = Square()
side_length = int(input("Enter side length: "))
print(figure.area(side_length))

But, as mentioned in the comments by Thomas, there is no real point in having the class if you don't do something like this:

class Square:
    def __init__(self, side_length):
        self.side_length = side_length
    def area(self):
        calc = self.side_length ** 2
        return calc

side_length = int(input("Enter side length: "))
figure = Square(side_length)
print(figure.area())

CodePudding user response:

You miss the self bro

class Square():
    def area(self, side_length):
        calc = side_length**2
        return calc

figure = Square()
side_length = int(input("Enter side length: "))
print(figure.area(side_length))

Remember, in Python OOP, every single function need to have self parameter.
  • Related