【问题标题】:Replicating the behaviour of setattr and delattr from dataclasses从数据类中复制 setattr 和 delattr 的行为
【发布时间】:2021-05-05 10:06:27
【问题描述】:

在观看 Raymond Hettinger 在 PyCon 2018 上的演讲时,Dataclasses: The code generator to end all code generators - PyCon 2018 提供了数据类如何在冻结数据类上实现 setattr 和 delattr 的示例:

def __setattr__(self, name, value):
    if type(self) is cls or name in ('name', 'address', 'zip_code', 'account_balance', 'active_orders'):
        raise FrozenInstanceError(f'Cannot assign to field {name!r}')
    super(cls, self).__setattr__(name, value)

def __delattr__(self, name):
    if type(self) is cls or name in ('name', 'address', 'zip_code', 'account_balance', 'active_orders'):
        raise FrozenInstanceError(f'Cannot delete field {name!r}')
    super(cls, self).__delattr__(name)

是否可以在没有数据类的情况下复制在 setattr 和 delattr 中调用 super() 的行为来模拟不变性?

【问题讨论】:

  • 你试过了吗?发生了什么?
  • ...你有代码吗?你到底在问什么?
  • @martineau 如果我在不使用数据类的情况下运行它,我会收到一个错误,即未定义 cls,所以我的问题是数据类如何在这些函数中访问 cls,是吗?可以在不使用数据类的情况下复制它吗?
  • 这只是类名的别名。这不是完整的代码,如果您使用的是 Python 3,则可以只使用不带参数的 super(),或者如果说,您正在定义 class Foo: ... 等效的 super(Foo, self).__whatever__。

标签: python python-3.x python-dataclasses


【解决方案1】:

正如@juanpa.arrivillaga 在评论中指出的那样,您可以使用内置的super() 函数复制该行为,但是您不需要将任何参数传递给它(至少在 Python 3 中)。 示例:

class Class:
    class FrozenInstanceError(Exception): pass

    fieldnames = 'name', 'address', 'zip_code', 'account_balance', 'active_orders'

    def __init__(self):
        super().__setattr__('account_balance', 0)  # Bypasses this class' __setattr__().

    def __setattr__(self, name, value):
        if isinstance(self, Class) and name in self.fieldnames:
            raise self.FrozenInstanceError(f'Cannot assign to field {name!r}')
        super().__setattr__(name, value)

    def __delattr__(self, name):
        if isinstance(self, Class) and name in self.fieldnames:
            raise self.FrozenInstanceError(f'Cannot delete field {name!r}')
        super().__delattr__(name)


if __name__ == '__main__':

    inst = Class()
    print(inst.account_balance)  # -> 0
    try:
        inst.account_balance = 1000000
    except Exception as exc:
        print(exc)  # -> Cannot assign to field 'account_balance'
    else:
        print('Error: Somehow assigned value to "account_balance" field')

    try:
        inst.something_else = 42  # OK, not a field name.
    except Exception as exc:
        print(exc)  # -> 'Error: Wasn't allowed to create "something_else" field'
    else:
        print('Successfully created "something_else" attribute.')  # Prints.

    try:
        del inst.account_balance
    except Exception as exc:
        print(exc)  # -> Cannot delete field 'account_balance'
    else:
        print('Error: Somehow deleted protected "account_balance" field')

    try:
        del inst.something_else
    except Exception as exc:
        print(exc)  # -> 42
    else:
        print('Successfully deleted "something_else" attribute.')  # Prints.

【讨论】:

  • 我对为什么不应该使用isinstance() 的看法是因为子类可能没有冻结特征,但可以委托给父类的__*attr()__。因此,数据类完成了“只有这个类,没有子类”检查。
  • @Alastair:你的看法是错误的。在这里使用isinstance() 很好,因为子类可以通过简单地将自己的fieldnames 类属性设置为其他东西来定义自己的冻结特征。在 Python 中进行显式类型检查几乎从来都不是一个好主意(例如 OP 的问题中显示的内容)。
猜你喜欢
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多