2017-09-05 24 views
0

我正在研究一个简单的员工系统,用于在Python3中学习面向对象的编程。 我的脚本正常工作,不包括保存和加载员工字典。 问题是我的字典不是这个代码的正常字典原因: Employees[eid] = Employee(eName,eSalary,eAge) 我想使这个数据库JSON可序列化,但我不知道,我也没有想到,我在互联网上发现它。Python3词典风格对象映射到JSON可序列化

可悲的是在堆栈溢出将系统代码给我的癌症,所以我贴我的代码要点: https://gist.github.com/ShockvaWe/d82d89f767506c1ff682a4cc387d1597

并与当前的代码我的错误消息(基本TypeEroor但...): 抱歉,我浪费我的2个小时试图粘贴我的代码,我失败了,所以我生气了。感谢编辑和答案。

下面是代码:

## -*- coding=<utf-8> -*- 
import json 
from json import JSONEncoder 
Employees = {} 
print(type(Employees)) 
class Employee(object): 
    'Common base for all employes' 
    empCount = 0 
    def __init__(self,name,salary,age): 
     self.name = name 
     self.salary = salary 
     self.age = age 
     Employee.empCount += 1 

    def displayCount(self): 
     print ("Total Employee : " , Employee.empCount , "\n") 

    def displayEmployee(self): 
     print("Name : ", self.name ," Salary : " , self.salary ," Age : " , self.age, "\n") 
print ("NEVER FORGET TO SAVE YOUR CHANGES ! \n") 
print ("Press s to save your work ! \n") 
print ("Press l to load database. \n") 
print ("Press x for adding employee \n") 
print ("Press y for show employee count \n") 
print ("Press z for display employee \n") 
print ("Press q for quitting. \n") 
while True : 
    st = input("->> : ") 
    if (st == "x"): 
     eid = input ("Id : ") 
     eName = input ("\nName : ") 
     eSalary = input ("\nSalary : ") 
     eAge = input ("\nAge : \n") 
     Employees[eid] = Employee(eName,eSalary,eAge) 
    if (st == "y"): 
     print("Total Employee Count : " , Employee.empCount) 
    if (st == "z"): 
     wantedId = input("Give the id : ") 
     Employees[wantedId].displayEmployee() 
    if (st == "q"): 
     exit() 
    if (st == "s"): 
     with open('myfile.json','w') as f: 
      json.dump(dict(Employees),f) 
    if (st == "l"): 
     with open('myfile.json') as f: 
      Employees = json.load(f) 
    if (st == 'f'): 
     print("roger dodger") 
+1

如果你想让你的问题得到解答,你可能不应该侮辱你发布的网站。我建议编辑您的帖子以更有礼貌。 –

+0

请编辑您的问题并删除最后一段。它的攻击性与你的问题无关。尝试再次编辑并包含您的代码。你知道,很多人使用这个网站,并且可以写出格式良好的问题。 – ventiseis

回答

0

下面是可能再现TypeError你看到一个小例子:

class Foo(object): 
    def __init__(self, arg): 
    self.arg = arg 

d = {'key1': Foo('some arg')} 
import json 

print json.dumps(d) 

通过他们的本质,Python class实例不是序列化。假设你想在类内的数据,一种选择是使用实例字典而不是类对象:

class Foo(object): 
    def __init__(self, arg): 
    self.arg = arg 

f = Foo('some arg') 
d = {'key1': f.__dict__} 
import json 

print json.dumps(d) 

结果:

{"key1": {"arg": "some arg"}} 

反序列化,您可以使用序列您DB和得到这个构造新的Employee对象,并跟踪这在你的JSON时,后来的“重建”他们:

import json 

class Employee(object): 
    def __init__(self, arg, emp_id=None): 
    self.emp_id = emp_id or self.get_id() 
    self.arg = arg 

    def get_id(self): 
    """ 
    This example assumes you have a db query module and some kind of Sequence 
    definition that looks like this (I am using postgres here) : 

     Sequence "your_app.employee_id_seq" 
     Column  | Type |   Value   
    ---------------+---------+-------------------------- 
    sequence_name | name | employee_id_seq 
    last_value | bigint | 1204 
    start_value | bigint | 1 
    increment_by | bigint | 1 
    max_value  | bigint | 9223372036854775807 
    min_value  | bigint | 1 
    cache_value | bigint | 1 
    log_cnt  | bigint | 31 
    is_cycled  | boolean | f 
    is_called  | boolean | t 
    """ 
    return your_db_module.query("SELECT nextval('employee_id_seq'::regclass)") 

一个试验:

f = Employee('some arg') 
d = {f.emp_id: f.__dict__} 
# We could add as many employees as we like to serialized, but I am just using one here: 
serialized = json.dumps(d) 
deserialized_employees = json.loads(serialized) 
print deserialized_employees 
employee_objects = [] 
for k, v in deserialized_employees.items(): 
    # assert int(k) == int(v['emp_id']) - a check if you want to be paranoid 
    # Now that we have an ID, we can use the kwarg for emp_id to construct the right object 
    e = Employee(v['arg'], emp_id=int(k)) 
    employee_objects.append(e) 

print employee_objects[0] 

结果:

<__main__.Employee object at 0x10dca6b50> 

请注意,您可能需要自定义的定义__cmp__和/或__eq__方法,以便让你的独特emp_id是一个独特的员工的决定性特征,因为在此电流在技​​术上,我们在技术上允许使用一个ID创建同一员工的许多实例(通常是一件坏事)。不知道这是否适用于您的案例,但值得考虑。

+0

是的,但是现在你如何将它反序列化为正确的对象呢? –

+0

由于这与DB相关,因此我会建议一个自动递增序列作为Employee的唯一标识符,然后将其传递给每个对象的初始化,并将其用作稍后反序列化的基础。你可以简单地根据你所拥有的字典来构建雇员。 – JacobIRR

+0

你也可以进行反序列化吗? –