问题描述
我浏览了网页和pydoc,但没有成功找到答案。 我的问题如下:
我想定义一个具有属性的类,就像我习惯做的那样。
class Container(object):
def __init__(self, content):
assert isinstance(content, dict), "The container can only contain a dictionary"
self._content = content
@property
def name():
try:
return self._content["its_name"]
except KeyError:
raise AttributeError
现在,要访问内容的字段“ its_name
”,我可以使用container.name
,在字段的名称和属性之间稍作修改。
我想在没有设置特定的getter属性时有一个默认行为。
我的意思是,如果我调用container.description
,我希望我的类尝试返回self._content["description"]
,如果没有这样的键,则抛出一个AttributeError
。
虽然仍然为container.name
案件调用特定属性。
在此先感谢您的帮助。
1楼
这就是__getattr__
特殊方法的用途:
def __getattr__(self, attrname):
# Only called if the other ways of accessing the attribute fail.
try:
return self._content[attrname]
except KeyError:
raise AttributeError
请注意,如果由于某种原因,当_content
属性不存在时,您尝试检索未知属性
return self._content[attrname]
将递归调用__getattr__
以尝试获取_content
属性,并且该调用将调用__getattr__
,依此类推,直到堆栈溢出。