Discuss / Python / 没整明白,为啥我的报错?

没整明白,为啥我的报错?

Topic source
在此插入代码
>>> class Student:
    def get_grade(self):
        self.score='54'
        if self.score>=90:
            return 'A'
        elif self.score>=60:
            return 'B'
        else:
            return 'C'


>>> a=Student
>>> a.get_grade()
Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    a.get_grade()
TypeError: get_grade() missing 1 required positional argument: 'self'

Lam-友

#2 Created at ... [Delete] [Delete and Lock User]

self.score='54' 不需要引号 self.score=54

string 和 int 不能做比较

a=Student a

<class '__main__.Student'> a=Student() a

<__main__.Student object at 0x101a2ca90>

不要随便就少敲两个字符啊!!括号是极为重要的语法关键字,看见括号就把肾上腺素升起来,不然就全是坑! 不用括号,赋值给a的是Student这个类本身 用了括号就变成了调用,先调用Student的构造函数,再将函数调用的结果(即返回的对象实例)赋值给a

谢谢两位大兄弟,我犯了个低级错误


  • 1

Reply