how i can call this class?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class average : def myinput(): n=0 mylist=[] #will be ended when input = -1 while n !='-1' : n=raw_input('>>>') if n!='-1' : mylist.append(n) print lol(mylist) def lol(mylist): try: mysum=0.0 for i in mylist : mysum=mysum+int(i) return mysum/len(mylist) except: return 'please don\'t Enter charecters just Number' ave=average ave.myinput() |
这个代码有什么问题?
$ winpty python test3.py Traceback (most recent call last):
File"test3.py", line 20, in
ave.myinput() TypeError: unbound method myinput() must be called with
average instance as firs t argument (got nothing instead)"""
你的课应该是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Average() : def myinput(self): n=0 mylist=[] #will be ended when input = -1 while n !='-1' : n=raw_input('>>>') if n!='-1' : mylist.append(n) print self.lol(mylist) def lol(self, mylist): try: mysum=0.0 for i in mylist : mysum = mysum + int(i) return mysum/len(mylist) except: return 'please don\'t Enter charecters just Number' ave = Average() ave.myinput() |
第一个参数应该是类实例本身。
首先应该重命名类,python命名约定非常强,类应该总是以大写字母开头。
然后回答:你只是忘记了
1 2 | ave = Average() ave.myinput() |
您应该在每个方法中放置类实例:
你漏了括号。
1 | ave=average() |