Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a class method raises a TypeError in Python

I don't understand how classes are used. The following code gives me an error when I try to use the class.

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)) 

Error:

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's wrong?

like image 663
stu Avatar asked Dec 28 '08 23:12

stu


People also ask

Can you call methods in __ init __?

You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method. The __str__ method is called when you print() an object.

What is __ call __ In Python class?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

What happens when you call a class in Python?

In Python, the syntax for instantiating a new class instance is the same as the syntax for calling a function. There's no new needed: we just call the class. When we call a function, we get its return value. When we call a class, we get an “instance” of that class.

What does the __ Add__ method do?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1. __add__(obj2). This works, because int implements the __add__() method behind the scenes.


1 Answers

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff() print x.average(9,18,27) 

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:

TypeError: average() takes exactly 3 arguments (4 given) 

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.

like image 102
Ryan Avatar answered Sep 21 '22 14:09

Ryan