0

假设我有以下课程

class Headings:
    standard_heading = {
        'height': 3.72,
        'width': 25.68,
        'left': 1.65,
        'top': 0.28
    }

例如,我想要以下结果,其中所有值都乘以 10:

Headings.standard_heading

>>> {
            'height': 37.2,
            'width': 256.8,
            'left': 16.5,
            'top': 2.8
        }

有没有办法通过向类添加类似这样的方法来覆盖类属性的调用:

def __getattribute__(cls, attr):
    return {k:v*10 for k,v in attr.items()

我永远不会创建此类的实例。我只是将它用于分组目的。

谢谢

4

3 回答 3

3

您几乎拥有它 - 只需将 getter 定义为类方法(还有一个小的语法错误,attr这里是一个字符串):

class Headings:
    standard_heading = {
        'height': 3.72,
        'width': 25.68,
        'left': 1.65,
        'top': 0.28
    }          
    @classmethod
    def __getattribute__(cls,attr):
        return {k:v*10 for k,v in cls.__dict__[attr].items()}

print(Headings().standard_heading)

请注意,您确实需要一个实际实例才能使其工作,但这就是您在示例中使用的。这也将破坏在对象的任何方法(例如__init__)中定义的对象特定字段的 get 属性,因此请小心。一个简单的解决方法是也覆盖:

@classmethod
def __getattribute__(cls,attr):
    try:
        return {k:v*10 for k,v in cls.__dict__[attr].items()}
    except: raise AttributeError(attr)
def __getattr__(self,attr):
    return object.__getattribute__(self,attr)

所以现在如果你有:

def __init__(self): self.a = 'abc'

然后

print(Headings().a)

也将工作。解释:

  1. 首先__getattribute__被称为类方法。
  2. 如果不存在类变量,则__getattr__调用 then,现在作为常规方法,对实际对象(和对象成员)也是如此。
  3. 调用object __getattribute__以恢复正常行为。

最后一点 - 除了你的具体问题,如果你只想getter为一个类成员定义一个特殊的,一种只会影响所述成员的更安全的方法正在使用@property@getter- 如@property 装饰器如何工作?. 感谢阿多尼斯指出这一点。

于 2018-04-10T12:22:55.880 回答
1

如果您想将此行为应用于许多不同的类,您可以创建一个父类。

class MultiplyBy10:
    def __getattribute__(self, attr):
        return {k:v*10 for k,v in super().__getattribute__(attr).items()}

class Headings(MultiplyBy10):
    standard_heading = {
        'height': 3.72,
        'width': 25.68,
        'left': 1.65,
        'top': 0.28
    }

h = Headings()
print(h.standard_heading)

将显示

{'height': 37.2, 'width': 256.8, 'left': 16.5, 'top': 2.8000000000000003}
于 2018-04-10T11:57:16.697 回答
0

如果您的要求是更改从字典返回的值,而不是创建另一个字典,您可能想要构建一个自定义 - :如何“完美”覆盖字典?

于 2018-04-10T12:12:44.760 回答