我想知道是否有一种合理简单的方法可以让这段代码(稍加修改)工作。
class Info(object):
@attr("Version")
def version(self):
return 3
info = Info()
assert info.version == 3
assert info["Version"] == 3
理想情况下,代码也会进行一些缓存/内存,例如使用惰性属性,但我希望自己能解决这个问题。
其他信息:
我想提供两个接口(interface)来访问相同的信息的原因如下。
我想要一个类似字典的类,它使用惰性键。例如。 info["Version"]
应该调用并缓存另一个方法并透明地返回结果。
我认为这不适用于字典,因此我需要创建新方法。
单独的方法也无法做到这一点,因为有些属性使用纯字典语法更容易定义。
无论如何,这可能不是最好的主意......
最佳答案
如果属性名称(version
)始终是字典键的小写版本(“Version”
),那么您可以这样设置:
class Info(object):
@property
def version(self):
return 3
def __getitem__(self,key):
if hasattr(self,key.lower()):
return getattr(self,key.lower())
如果您希望 dict 键是任意的,那么它仍然是可能的,尽管更复杂:
def attrcls(cls):
cls._attrdict={}
for methodname in cls.__dict__:
method=cls.__dict__[methodname]
if hasattr(method,'_attr'):
cls._attrdict[getattr(method,'_attr')]=methodname
return cls
def attr(key):
def wrapper(func):
class Property(object):
def __get__(self,inst,instcls):
return func(inst)
def __init__(self):
self._attr=key
return Property()
return wrapper
@attrcls
class Info(object):
@attr("Version")
def version(self):
return 3
def __getitem__(self,key):
if key in self._attrdict:
return getattr(self,self._attrdict[key])
我想更大的问题是,这是一个好的界面吗?为什么要为同一事物提供两种语法(具有两个不同的名称)?
关于Python 装饰器类将方法转换为字典项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3289064/