我正在尝试使用带有python字典的类

时间:2016-12-20 16:08:57

标签: python python-3.x dictionary

class student(object):
    def __init__(self, name, age, year):
        self.name, self.age, self.year = name, age, year
        self.grades=[]
        self.grade={}
        print(name,'-------->','Age:',age,'','Year:',year)

    def set_grades(self,score):
        self.grades.append(score)
    def get_grades(self):
        return self.grades
    def average(self):
        return sum(self.grades)/len(self.grades)
    def topgrade(self,other):
        return max(self.average(),other.average())


    def __str__(self):
        return str(self.name)+'--'+' Grades:'+str(self.grades)+'---Class average:'+str(self.average())

    def dicts(self):
        return grade[self.name]=self.grades


todd=student('Todd', 43, 4)
leah=student('Leah', 38,3)

当我运行代码时出现错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\toddb\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)
  File "C:\Users\toddb\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)
  File "C:/Users/toddb/Desktop/student.py", line 32
    return grade[self.name]=self.grades
                           ^
SyntaxError: invalid syntax

我试过这几种方式。我只限于使用清单吗?

2 个答案:

答案 0 :(得分:3)

那是因为你无法在Python中返回作业的结果:

class Test(object):
    pass

a = Test()
somevariable = a.attr = 10

有效 - 但只要你想要退货:

def func():
    a = Test()
    return a.testattr = 10

>>> func()
SyntaxError: invalid syntax

甚至更容易:

def func():
    return a = 0

>>> func()
SyntaxError: invalid syntax

所以你需要拆分作业和回报:

def dicts(self):
    grade[self.name]=self.grades
    return grade

请注意,当您尝试调用此函数时,这将引发NameError(除了您有一个名为grade的全局变量)。但你可能意味着self.grade

def dicts(self):
    self.grade[self.name]=self.grades
    return self.grade

这反过来会永久改变你的self.grade词典。如果您不想要,可以在分配前创建副本:

def dicts(self):
    grade = self.grade.copy()
    grade[self.name]=self.grades
    return grade

答案 1 :(得分:0)

它是grade中声明的__init__字典吗?然后它应该说self.grade[self.name]=self.grades,否则在使用grades = {}作为字典之前在dicts方法中执行此grades