对于类(不是实例)变量,是否有类似 '__getattribute__' 的方法?

Tre*_*vor 7 python

我有一个类sysprops,我想在其中包含许多常量。但是,我想从数据库中提取这些常量的值,所以我想在访问这些类常量之一时使用某种钩子(类似于实例变量的getattribute方法)。

class sysprops(object):
    SOME_CONSTANT = 'SOME_VALUE'

sysprops.SOME_CONSTANT  # this statement would not return 'SOME_VALUE' but instead a dynamic value pulled from the database.
Run Code Online (Sandbox Code Playgroud)

Wes*_*sie 2

而其他两个答案都有一个有效的方法。我喜欢走“最少魔法”的路线。

您可以执行类似于元类方法的操作,而无需实际使用它们。只需使用装饰器即可。

def instancer(cls):
    return cls()

@instancer
class SysProps(object):
    def __getattribute__(self, key):
        return key # dummy
Run Code Online (Sandbox Code Playgroud)

这将创建一个实例SysProps,然后将其分配回名称SysProps。有效地隐藏实际的类定义并允许常量实例。

由于装饰器在 Python 中更常见,我发现这种方式对于其他必须阅读您的代码的人来说更容易掌握。