简体   繁体   English

使用装饰器编码自定义对象-Python

[英]Encoding custom objects with decorators - Python

I am looking for a way to encode custom objects to dict in Python using a class decorator to provide the name of the variables that should be included in the resulting dict as arguments. 我正在寻找一种使用类装饰器将自定义对象编码为dict的方法,以提供应包含在结果dict中的变量名称作为参数。 With the dict, I would be able to use json.dumps(custom_object_dict) to make the transformation to JSON. 有了dict,我将能够使用json.dumps(custom_object_dict)进行JSON转换。

In other words, the idea is to have the following @encoder class decorator: 换句话说,想法是拥有以下@encoder类装饰器:

@encoder(variables=['firstname', 'lastname'], objects=['professor'], lists=['students'])
class Course(Object):
   def __init__(self, firstname, lastname, professor, students):
        self.firstname = firstname
        self.lastname = lastname
        self.professor = professor
        self.students = students

#instance of Course:
course = Course("john", "smith", Professor(), [Student(1), Student(2, "john")])

This decorator would allow me to do something similar to the following: 该装饰器将允许我执行以下操作:

Option A: 选项A:

json = json.dumps(course.to_dict())

Option B: 选项B:

json = json.dumps(course.dict_representation)

...Or something of the like ...或类似的东西

So the question is: How to write this encoder, where the only real requirements are: 因此,问题是:如何编写此编码器,唯一真正的要求是:

  1. Encoder should only encode variables that are provided through the decorator 编码器应仅对通过装饰器提供的变量进行编码
  2. Encoder should be able to encode other objects (eg: professor inside Courses, if the Professor class also has the decorator @encoder 编码器应该能够对其他对象进行编码(例如:如果“教授”类也具有装饰器@encoder ,则“课程内的教授”
  3. Should also be able to encode a list of other objects (eg: students inside course, counting that the class Students would also have to @encoder decorator) 还应该能够对其他对象的列表进行编码(例如:课程中的学生,认为该班学生也必须@encoder装饰器)

I have researched different ways of doing that (including creating a class that inherits from json.JSONEncoder), but none seemed to do exactly what I had in mind. 我研究了不同的方法(包括创建一个从json.JSONEncoder继承的类),但是似乎没有一种方法可以完全实现我的想法。 Would anyone be able to help me? 谁能帮助我?

Thanks in advance! 提前致谢!

Maybe something like this (just a fast sketch): 也许是这样的(只是一个快速的草图):

#! /usr/bin/python3.2

import json

class Jsonable:
    def __init__ (self, *args):
        self.fields = args

    def __call__ (self, cls):
        cls._jsonFields = self.fields
        def toDict (self):
            d = {}
            for f in self.__class__._jsonFields:
                v = self.__getattribute__ (f)
                if isinstance (v, list):
                    d [f] = [e.jsonDict if hasattr (e.__class__, '_jsonFields') else e for e in v]
                    continue
                d [f] = v.jsonDict if hasattr (v.__class__, '_jsonFields') else v
            return d
        cls.toDict = toDict

        oGetter = cls.__getattribute__
        def getter (self, key):
            if key == 'jsonDict': return self.toDict ()
            return oGetter (self, key)
        cls.__getattribute__ = getter

        return cls

@Jsonable ('professor', 'students', 'primitiveList')
class Course:
    def __init__ (self, professor, students):
        self.professor = professor
        self.students = students
        self.toBeIgnored = 5
        self.primitiveList = [0, 1, 1, 2, 3, 5]

@Jsonable ('firstname', 'lastname')
class Student:
    def __init__ (self, firstname, lastname, score = 42):
        self.firstname = firstname
        self.lastname = lastname
        self.score = score

@Jsonable ('title', 'name')
class Professor:
    def __init__ (self, name, title):
        self.title = title
        self.name = name

p = Professor ('Ordóñez', 'Dra')
s1 = Student ('Juan', 'Pérez')
s2 = Student ('Juana', 'López')
s3 = Student ('Luis', 'Jerez')
s4 = Student ('Luisa', 'Gómez')
c = Course (p, [s1, s2, s3, s4] )

print (json.dumps (c.jsonDict) )

You might want to check for other iterables besides list or something like if hasattr (v, __iter__) and not isinstance (v, str) . 您可能要检查list以外的其他可迭代对象,或诸如hasattr (v, __iter__) and not isinstance (v, str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM