Calling a class method raises a TypeError in Python

前端 未结 8 672
小鲜肉
小鲜肉 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 17:01

    Every function inside a class, and every class variable must take the self argument as pointed.

    class mystuff:
        def average(a,b,c): #get the average of three numbers
                result=a+b+c
                result=result/3
                return result
        def sum(self,a,b):
                return a+b
    
    
    print mystuff.average(9,18,27) # should raise error
    print mystuff.sum(18,27) # should be ok
    

    If class variables are involved:

     class mystuff:
        def setVariables(self,a,b):
                self.x = a
                self.y = b
                return a+b
        def mult(self):
                return x * y  # This line will raise an error
        def sum(self):
                return self.x + self.y
    
     print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
     print mystuff.mult() # should raise error
     print mystuff.sum()  # should be ok
    

提交回复
热议问题