创建每个实例的属性描述符?

Wai*_*ung 8 python metaprogramming propertydescriptor

通常Python描述符被定义为类属性.但在我的情况下,我希望每个对象实例都有不同的设置描述符,这取决于输入.例如:

class MyClass(object):
  def __init__(self, **kwargs):
    for attr, val in kwargs.items():
      self.__dict__[attr] = MyDescriptor(val)
Run Code Online (Sandbox Code Playgroud)

每个对象都具有在实例化时确定的不同属性集.由于这些是一次性对象,因此首先将它们子类化是不方便的.

tv = MyClass(type="tv", size="30")
smartphone = MyClass(type="phone", os="android")

tv.size   # do something smart with the descriptor
Run Code Online (Sandbox Code Playgroud)

将描述符分配给对象似乎不起作用.如果我尝试访问该属性,我会得到类似的东西

<property at 0x4067cf0>
Run Code Online (Sandbox Code Playgroud)

你知道为什么这不起作用吗?有什么工作吗?

Use*_*ser 3

这是行不通的,因为您必须将描述符分配给对象的类。

class Descriptor:

    def __get__(...):
        # this is called when the value is got

    def __set__(...
    def __del__(...
Run Code Online (Sandbox Code Playgroud)

如果你写

obj.attr
=> type(obj).__getattribute__(obj, 'attr') is called
=> obj.__dict__['attr'] is returned if there else:
=> type(obj).__dict__['attr'] is looked up
if this contains a descriptor object then this is used.
Run Code Online (Sandbox Code Playgroud)

所以它不起作用,因为在类型字典中查找描述符而不是对象字典。

有可能的解决方法:

  1. 将描述符放入类中并使其使用例如 obj.xxxattr 来存储值。如果只有一种描述符行为,则此方法有效。

  2. 覆盖setattrgetattrdelattr以响应描述符。

  3. 将描述符放入响应对象字典中存储的描述符的类中。