Python 在dict对象上调用类方法:AttributeError:';dict';对象没有属性';获取"keyval"';
是否可以获取Python 在dict对象上调用类方法:AttributeError:';dict';对象没有属性';获取"keyval"';,python,json,python-3.x,dictionary,inheritance,Python,Json,Python 3.x,Dictionary,Inheritance,是否可以获取filter\u dict对象类型的关键字值。获取关键字值(“作者”): 获取: AttributeError: 'dict' object has no attribute 'get_keyval' 做了以下变通(但这不是我想要的): Config().open\u json\u file返回的对象类型不是Config,而是json.loads返回的普通dict。基本上,Config不是一个类,而是一组编码为方法的函数。您想要的可能是: import json class Co
filter\u dict
对象类型的关键字值。获取关键字值(“作者”):
获取:
AttributeError: 'dict' object has no attribute 'get_keyval'
做了以下变通(但这不是我想要的):
Config().open\u json\u file
返回的对象类型不是Config
,而是json.loads
返回的普通dict。基本上,Config
不是一个类,而是一组编码为方法的函数。您想要的可能是:
import json
class Config(dict): # derive from dict to gain get and constructor
@classmethod
def from_json_file(cls, json_string):
"""Initialize Config dict from a JSON string"""
load_dict = json.loads(json_string)
return cls(load_dict) # create new Config (dict) filled with JSON content
def get_keyval(self, key):
return self.get(key)
filter_dict = Config.from_json_file(...)
print(filter_dict.get_keyval("author")) # you might want to just call plain filter_dict.get("author") here
Config().open\u json\u file
返回的对象类型不是Config
,而是json.loads
返回的普通dict。基本上,Config
不是一个类,而是一组编码为方法的函数。您想要的可能是:
import json
class Config(dict): # derive from dict to gain get and constructor
@classmethod
def from_json_file(cls, json_string):
"""Initialize Config dict from a JSON string"""
load_dict = json.loads(json_string)
return cls(load_dict) # create new Config (dict) filled with JSON content
def get_keyval(self, key):
return self.get(key)
filter_dict = Config.from_json_file(...)
print(filter_dict.get_keyval("author")) # you might want to just call plain filter_dict.get("author") here
您没有正确使用类方法。你不想每次调用一个类方法时都创建一个新的类实例——这太疯狂了。在这种情况下,您甚至不需要类方法,而是需要静态方法。因此,添加
@staticmethod
装饰器,然后在不调用构造函数的情况下调用该方法?您只是在包装现有对象的功能filter\u dict=json.load(“…”)
和print(filter\u dict.get(“author”)
是等效的,不需要类。您没有正确使用类方法。你不想每次调用一个类方法时都创建一个新的类实例——这太疯狂了。在这种情况下,您甚至不需要类方法,而是需要静态方法。因此,添加@staticmethod
装饰器,然后在不调用构造函数的情况下调用该方法?您只是在包装现有对象的功能filter\u dict=json.load(“…”)
和print(filter\u dict.get(“author”)
是等效的,不需要类。还请注意,只需在类定义中执行get_keyval=dict.get
,就足以为该方法创建别名。@Tadhgmonard Jensen在我的示例中,您是对的,但我有一个更大的json文件,我想在dict对象中搜索键并返回其值。还请注意类定义中的get\u keyval=dict.get
足以为该方法创建别名。@Tadhgmald Jensen在我的示例中你是对的,但我有一个更大的json文件,我想在dict对象中搜索键并返回其值。
import json
class Config(dict): # derive from dict to gain get and constructor
@classmethod
def from_json_file(cls, json_string):
"""Initialize Config dict from a JSON string"""
load_dict = json.loads(json_string)
return cls(load_dict) # create new Config (dict) filled with JSON content
def get_keyval(self, key):
return self.get(key)
filter_dict = Config.from_json_file(...)
print(filter_dict.get_keyval("author")) # you might want to just call plain filter_dict.get("author") here