gpt4 book ai didi

python - 列出当前存在的所有类

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:07 25 4
gpt4 key购买 nike

我正在创建一个简单的 API,它基于 JSON 数据创建类型化类,其中定义了一个强制性的“类型”字段。它使用此字符串定义新类型,在 JSON 对象中添加字段,实例化它,然后填充实例上的字段。

我希望能够做的是允许在使用我的模块的任何应用程序中选择性地预定义这些类型。这样就可以添加在 JSON 对象中找不到的方法和其他特定于应用程序的属性。我想让我的模块检查一个类型是否已经存在,如果存在,则使用它而不是动态创建该类型。它仍会从 JSON 对象添加属性,但会回收现有类型。

我的 JSON 数据是:

{
"type": "Person",
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}

到目前为止我的代码(假设此时 json_object 是一个字典):

if not json_object.has_key('type'):
raise TypeError('JSON stream is missing a "type" attribute.')

##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY ####
# create a type definition and add attributes to it
definition = type(json_object['type'], (object,), {})
for key in json_object.keys():
setattr(definition, key, None)

# instantiate and populate a test object
tester = definition()
for key, value in json_object.iteritems():
setattr(tester, key, value)

最佳答案

如果你想重用之前创建的类型,最好自己缓存它们:

json_types = {}
def get_json_type(name):
try:
return json_types[name]
except KeyError:
json_types[name] = t = type(json_object['type'], (object,), {})
# any further initialization of t here
return t

definition = get_json_type(json_object['type'])
tester = definition()
# or: tester = get_json_type(json_object['type'])()

如果你想将它们添加到模块命名空间,做

json_types = globals()

相反。

关于python - 列出当前存在的所有类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/373067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com