Calling a class method raises a TypeError in Python

前端 未结 8 648
小鲜肉
小鲜肉 2020-12-04 16:02

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 th         


        
8条回答
  •  一向
    一向 (楼主)
    2020-12-04 16:52

    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.

提交回复
热议问题