有没有办法在运行时将描述符分配给实例属性?
Is there a way to assign a descriptor to an instance attribute at runtime?
这个问题在 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)
是否可以在运行时将此描述符的实例分配给其他 class 实例,并使其行为符合描述符协议?
天真的方法失败了:
foo.thing = MyThing()
foo.thing
不像描述符,它只是像典型的实例属性。
这不是 XY 问题。正如我所说的,我特意要求回答这个问题。
不,描述符协议仅在描述符对象是 class 的成员时才有效,这表示为 int the HOWTO:
To use the descriptor, it must be stored as a class variable in
another class
或者,来自 data model docs:
The following methods only apply when an instance of the class
containing the method (a so-called descriptor class) appears in an
owner class (the descriptor must be in either the owner’s class
dictionary or in the class dictionary for one of its parents).
这个问题在 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)
是否可以在运行时将此描述符的实例分配给其他 class 实例,并使其行为符合描述符协议?
天真的方法失败了:
foo.thing = MyThing()
foo.thing
不像描述符,它只是像典型的实例属性。
这不是 XY 问题。正如我所说的,我特意要求回答这个问题。
不,描述符协议仅在描述符对象是 class 的成员时才有效,这表示为 int the HOWTO:
To use the descriptor, it must be stored as a class variable in another class
或者,来自 data model docs:
The following methods only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents).