使用Python“json”模块生成类serializab

2024-10-05 14:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中使用了一个Email()类,我想将它扩展为SerializeEmail()类,它只需添加两个进一步的方法,.write\u Email()和.read_Email()。我喜欢这种行为:

# define email
my_email = SerializeEmail()
my_email.recipients = 'link@hyrule.com'
my_email.subject = 'RE: Master sword'
my_email.body = "Master using it and you can have this."
# write email to file system for hand inspection
my_email.write_email('my_email.txt')
...
# Another script reads in email
my_verified_email = SerializeEmail()
my_verified_email.read_email('my_email.txt')
my_verified_email.send()

我已经导航了json编码/解码过程,我可以成功地编写SerializeEmail()对象并将其读入,但是,我找不到一种通过SerializeEmail.read_电子邮件()打电话。在

^{pr2}$

问题是json.load文件在my read_email()方法中的()call返回SerializeEmail对象的一个实例,但不将该对象分配给我用来调用它的当前实例。所以现在我得做些类似的事情

another_email = my_verified_email.read_email('my_email.txt')

当我想要的是打电话给我的朋友时_email.read_电子邮件()用文件中的数据填充my_verified_电子邮件的当前实例。我试过了

self = json.load(f,cls=SerializeEmailJSONDecoder)

但那不管用。我可以将返回对象的每个元素都分配给“self”对象,但这似乎是临时的和不雅的,我正在寻找“正确的方法”来完成这个任务,如果它存在的话。有什么建议吗?如果你认为我的整个方法是有缺陷的,并推荐一种不同的方法来完成这项任务,请给我勾勒一下。在


Tags: 对象实例方法mastertxtjsonread电子邮件
1条回答
网友
1楼 · 发布于 2024-10-05 14:27:33

虽然您可以通过许多步骤将序列化内容加载到现有实例中,但我不建议这样做。这是一个不必要的复杂问题,它实际上不会给您带来任何好处;这意味着每次您想从JSON加载电子邮件时,都需要额外的步骤来创建一个虚拟实例。我建议使用工厂类或工厂方法,从序列化的JSON加载电子邮件并将其作为新实例返回。我个人的偏好是工厂方法,您可以按如下方式完成:

class SerializeEmail(Email):

    def write_email(self,file_name):

        with open(file_name,"w") as f:
            json.dump(self,f,cls=SerializeEmailJSONEncoder,sort_keys=True,indent=4)

    @staticmethod
    def read_email(file_name):

        with open(file_name,"r") as f:
           return json.load(f,cls=SerializeEmailJSONDecoder)

# You can now create a new instance by simply doing the following:
new_email = SerializeEmail.read_email('my_email.txt')

注意@staticmethod修饰符,它允许您在不传入任何隐式第一个参数的情况下调用类上的方法。通常工厂方法是@classmethods,但由于是从JSON加载对象,所以隐式类参数是不必要的。在

注意,通过这个修改,在从JSON加载另一个对象之前,不需要实例化一个SerializeEmail对象。您只需直接在类上调用该方法并获得所需的行为。在

相关问题 更多 >