Calling a class method raises a TypeError in Python

前端 未结 8 664
小鲜肉
小鲜肉 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:42

    To minimally modify your example, you could amend the code to:

    class myclass(object):
            def __init__(self): # this method creates the class object.
                    pass
    
            def average(self,a,b,c): #get the average of three numbers
                    result=a+b+c
                    result=result/3
                    return result
    
    
    mystuff=myclass()  # by default the __init__ method is then called.      
    print mystuff.average(a,b,c)
    

    Or to expand it more fully, allowing you to add other methods.

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

提交回复
热议问题