Power a number with input() and function within class

Question:

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)
Asked By: Mamed

||

Answers:

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))
Answered By: Omid

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())
Answered By: The Thonnu

You’re missing self:

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.

Answered By: Kukushaa
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

Answered By: MoRe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.