Python 装饰器类将方法转换为字典项

标签 python properties decorator

我想知道是否有一种合理简单的方法可以让这段代码(稍加修改)工作。

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/

相关文章:

python - Google App Engine - 保护 cron python 的 url

node.js - NestJs - 从自定义装饰器内的服务调用方法

python - 重新排序数据透视表的列/行?

c#-3.0 - C#3.0 自动属性,为什么不直接访问字段呢?

python - 使用 python 将视频中的帧范围替换为图像

java - 将值设置/放入Spring-boot的Spring环境中以供以后使用

c# - 为什么 'stackalloc' 关键字不适用于属性?

.net - 在 Windsor 中注册通用装饰器

python - 如何在 Tensorflow 训练期间将 [3751,4] 数据集密集并 reshape 为 [1,6] 数据集

python - 在Python中填充二维数组的有效方法