2017-09-05 47 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

你也可以進行反序列化嗎? –