-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
121 lines (101 loc) · 2.46 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import sys, json
class Class:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
@staticmethod
def from_students_json(data):
if data is None:
return
class_tmp = Class()
for item in data:
student = Student.from_json(item)
class_tmp.add_student(student)
return class_tmp
def print_all_student(self):
for student in self.students:
student.print()
def to_json(self):
data = []
for student in self.students:
data.append(student.to_json())
return data
def write_json(self, path):
with open(path, 'w') as file:
json.dump(self.to_json(), file)
class Student:
def __init__(self, id=-1, name=""):
self.id = id
self.name = name
@staticmethod #decorator
def from_json(data):
student = Student()
if data is None:
return
student.id = str(data['id'])
student.name = data['name']
return student
def to_json(self):
data = {
'id': self.id,
'name': self.name
}
return data
def print(self):
print("Student id: {}, name: {}".format(self.id, self.name))
def main():
class_a = Class()
with open('./config.json', 'r') as file:
data = json.loads(file.read())
class_a = Class.from_students_json(data)
if sys.argv[1] == "add_student":
id = sys.argv[2]
name = sys.argv[3]
student = Student(id, name)
class_a.add_student(student)
class_a.write_json('./config.json')
elif sys.argv[1] == 'print_students':
class_a.print_all_student()
if __name__ == "__main__":
main()
# class_b = Class.from_students_json([
# {
# "id": 1234,
# "name": "sxxx"
# },
# {
# "id": 1234,
# "name": "sxxx"
# }
# ])
#
#
# a = Student(100, "redhuang")
# b = Student(120, "chocolate")
# c = Student(123, "123")
# d = Student.from_json({
# "id": 1234,
# "name": 'rexhuang'
# })
#
# class_a = Class()
# class_a.add_student(a)
# class_a.add_student(b)
# class_a.add_student(c)
# class_a.add_student(d)
#
# class_a.print_all_student()
#
# class_b = Class.from_students_json([
# {
# "id": 1234,
# "name": "sxxx"
# },
# {
# "id": 1234,
# "name": "sxxx"
# }
# ])
# class_b.print_all_student()
#