python怎么存储数据_Python:如何在类中存储数据并继承
我對(duì)課程很陌生,我已經(jīng)寫了一個(gè)班來做熊貓的操作。
@分類方法
,但我不知道如何使用它們。
我的班級(jí)目標(biāo):
我想寫一個(gè)權(quán)限類。它應(yīng)該加載/寫入一個(gè)json文件,并且應(yīng)該能夠添加更多的權(quán)限。
編輯:
讀了一段時(shí)間后,我發(fā)現(xiàn)
staticmethod
還有一個(gè)
__init__
在初始化期間加載文件的。
class Permission:
data = None
def __init__(self, path):
if Permission.data is None:
self.read_permissions(path)
@staticmethod
def read_permissions(path):
try:
with open(path, 'r') as read_file:
Permission.data = json.load(read_file)
except FileNotFoundError as e:
logging.error(e)
sys.exit(1)
def add_permissions(self, group, level, permissions):
self.data['groups'].append({
'group': group,
'level': level,
'permissions': permissions
})
所以我可以像這樣使用這個(gè)類:
json_path = 'C:\\data\\test.json'
test_perm = Permission(json_path)
print(test_perm.data)
{'groups': [{'group': 'common', 'permissions': {'select_sample_x': True, 'select_sample_y': True, 'assign_x': False, 'request_y': True}}]}
test_perm.add_permissions('guys', 10, {'can_do_icecream': False, 'can_do_nothing': True})
print(test_perm.data)
{'groups': [{'group': 'pkf_common', 'permissions': {'select_sample_debitor': True, 'select_sample_creditor': True, 'assign_third_party_confirmation': False, 'request_reporting': True}}, {'group': 'guys', 'level': 10, 'permissions': {'can_do_icecream': False, 'can_do_nothing': True}}]}
總結(jié)
以上是生活随笔為你收集整理的python怎么存储数据_Python:如何在类中存储数据并继承的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 获取referer中的请求参数_Serv
- 下一篇: c语言程序前言,C语言 程序代码编写规范