【问题标题】:Is there a way to assign a descriptor to an instance attribute at runtime?有没有办法在运行时将描述符分配给实例属性?
【发布时间】:2021-02-01 20:34:20
【问题描述】:

这个问题在 2016 年被问到,但没有得到回答:Can a descriptor be assigned to an instance attribute instead of a class attribute?

我有一个基本描述符

class MyThing:
    def __set_name__(self, owner, name):
        print(f'Assigned to {name} on {owner}')
        self.name = name

    def __get__(self, obj, typ):
        print(f'Getting {self.name} on {obj}')
        return getattr(obj, self.name)

    def __set__(self, obj, val):
        print(f'Setting {self.name} on {obj} to {val}')
        setattr(obj, self.name, val)

是否可以在运行时将此描述符的实例分配给其他类实例,并使其行为符合描述符协议?

天真的方法失败了:

foo.thing = MyThing()

foo.thing 的行为不像一个描述符,它只是像一个典型的实例属性。

这不是 XY 问题。正如我所说的那样,我特意要求回答这个问题。

【问题讨论】:

  • 您是否正在寻找“mixins”?也许像this 这样的东西。不过,根据那个建议,我不太确定“在运行时”
  • @roganjosh 我特意询问这是否可以在运行时实现,正如我在问题中所描述的那样。如果答案是“否”,那么答案是“否”。
  • 当然你可以为实例属性分配一个描述符,但是描述符协议不会考虑这个

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


【解决方案1】:

不,描述符协议仅在描述符对象是类的成员时才有效,这在 int the HOWTO 中声明:

要使用描述符,它必须作为类变量存储在 另一个班级

或者,来自data model docs

以下方法仅适用于类的实例 包含方法(所谓的描述符类)出现在 所有者类(描述符必须在所有者的类中 字典或在其父母之一的类字典中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多