When I try this code:
class MyStuff: def average(a, b, c): # Get the average of three numbers result = a + b + c result = result / 3 return result # Now use the function `average` from the `MyStuff` class print(MyStuff.average(9, 18, 27))
I get an error that says:
File "class.py", line 7, in <module> print(MyStuff.average(9, 18, 27)) TypeError: unbound method average() must be called with MyStuff instance as first argument (got int instance instead)
What does this mean? Why can’t I call average this way?
You can instantiate the class by declaring a variable and calling the class as if it were a function:
However, this won’t work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you’ll see this error message:
To fix this, you’ll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.