【发布时间】:2017-09-05 19:21:52
【问题描述】:
我正在开发一个简单的员工系统,用于学习 Python3 中的面向对象编程。
我的脚本按预期工作,不包括保存和加载员工字典。
问题是我的字典不是此代码的正常字典原因:
Employees[eid] = Employee(eName,eSalary,eAge)
我想让这个数据库 JSON 可序列化,但我不知道也没有在互联网上找到它。
遗憾的是,堆栈溢出中的代码添加系统让我患上了癌症,所以我将代码粘贴到 gist 中: 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")
【问题讨论】:
-
如果你想回答你的问题,你可能不应该侮辱你发布它的网站。我建议编辑你的帖子更有礼貌。
-
请编辑您的问题并删除最后一段。它令人反感,与您的问题无关。尝试再次编辑它并包含您的代码。你知道,很多人使用这个网站并且可以写出格式正确的问题
标签: python json serialization