Ragecoder Ragecoder - 3 months ago 9
Python Question

Why doesn't this instance of this class's method take this argument?

My question is why I can't make a object of the class giving it an integer as an argument. It totally ignores the value that I pass as an argument to it. Yet, if I call the area function from the class and pass the same number into it's parentheses it will output the desired result of 144.

My best guess from what I have read so far is that the way the classes function is coded is incorrect for what I am hoping that it will achieve. Do I need to have the area function take it's argument like:

self.length
?

# -*- coding: utf-8 -*-
class square:
sides = 4
def __init__(self, length):
self.length = length
def area(self, length):
return length * length

box = square(12)
print(box.area())


Output:
TypeError: area() missing 1 required positional argument: 'length'


Shouldn't the object that is created save the value that is given to it for the duration of that objects life? Why does it throw another error when I tell it to print from the area method a second time if the calls looked like this?

print(box.area(12))
output:144
print(box.area())
output: <bound method square_shape.area of <__main__.square_shape object at 0x7f5f88355b70>>


I'm sorry if this question is a little oddly phrased but I'm simply looking for as much information as I can get and attempting to gain a better understanding of what I'm doing here. Other questions on this subject didn't give a good grasp of what I'm trying to figure out.

Answer

You are thinking of self.length. length (without a "self." in front of it) is just a local variable. If it's an argument, you need to provide it.

What you probably want is: def area(self): return self.length * self.length