Calling a class method raises a TypeError in Python

前端 未结 8 628
小鲜肉
小鲜肉 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
    
    0 讨论(0)
  • 2020-12-04 17:03

    From your example, it seems to me you want to use a static method.

    class mystuff:
      @staticmethod
      def average(a,b,c): #get the average of three numbers
        result=a+b+c
        result=result/3
        return result
    
    print mystuff.average(9,18,27)
    

    Please note that an heavy usage of static methods in python is usually a symptom of some bad smell - if you really need functions, then declare them directly on module level.

    0 讨论(0)
提交回复
热议问题