为什么在下面的代码中未定义错误名称“ student2dict”

时间:2018-07-19 03:59:12

标签: python

我现在才开始学习python。以下是我尝试测试的一些代码。 我的问题是: 现在,这些代码有一个错误: 当运行到student2dict行时,名称std_data未定义。 有人可以帮我弄清楚该如何解决吗?非常感谢。

import json

class Student(object):

    def __init__(self,name,age,score):
        self.name = name
        self.age = age
        self.score = score

    def student2dict(std):
        return{
            'name':std.name,
            'age':std.age,
            'score':std.score
            }

s= Student('Penny',20,88)
std_data = json.dumps(s,default=student2dict)
print('Dump Student:',std_data)

1 个答案:

答案 0 :(得分:2)

现有代码的问题在于,您没有名为student2dict的全局函数(或其他任何函数),因为您在class Student定义下缩进了该函数。

只需使其凹陷即可,它将起作用:

class Student(object):

    def __init__(self,name,age,score):
        self.name = name
        self.age = age
        self.score = score

def student2dict(std):
    return{
        'name':std.name,
        'age':std.age,
        'score':std.score
        }

s= Student('Penny',20,88)
std_data = json.dumps(s,default=student2dict)
print('Dump Student:',std_data)

但是,似乎您希望它是一种方法,而不是简单的函数:

  

在我尝试使用default = s.student2dict而不是dedault = student2dict

之前

常规方法需要一个self参数。这样就可以知道您正在调用哪个实例。您得到的错误大概是关于在调用带有两个参数的{{1}中的student2dict,而s又传递了相同的s.student2dict时调用了两个参数)只想要一个(s)。

您可以解决此问题:

json.dumps

现在您可以通过std,它将起作用。

但这确实不是一个很好的设计。如果您实际上没有使用class Student(object): def __init__(self,name,age,score): self.name = name self.age = age self.score = score def student2dict(self, std): return{ 'name':std.name, 'age':std.age, 'score':std.score } 做任何事情,那么您实际上并没有编写实例方法。


(您可以将其设置为static method,因为他们既不需要也不需要default=s.student2dict,但是我认为在这里没有任何意义。如果那是您想要的,全局函数可能更有意义。)


但是...如果您摆脱self而改用self怎么办?

std

现在,您不想传递self,因为这是实例class Student(object): def __init__(self,name,age,score): self.name = name self.age = age self.score = score def student2dict(self): return{ 'name':self.name, 'age':self.age, 'score':self.score } 所拥有的绑定方法。不能用参数调用它,因为该参数已经绑定了。关于两个参数而不是一个,您将得到相同的错误。

您想要的是一个未绑定方法,您可以通过在 class 而不是实例上引用它来获得它,以便以后可以在任何实例中调用它。像这样:

s.student2dict

之所以可行,是因为ss= Student('Penny',20,88) std_data = json.dumps(s,default=Student.student2dict) print('Dump Student:',std_data) 的作用相同。因此,如果将Student.student2dict(s)传递给s.student2dict(),当它在Student.student2dict上调用它时,您将得到所需的东西。