我可以得到“所有者”的参考吗?描述符的 __init__ 方法期间的类?
是否可以在描述符的 __init__ 函数期间访问描述符内的“所有者”类,而无需像本示例中那样手动传递它?
class FooDescriptor(object):
def __init__(self, owner):
#do things to owner here
setattr(owner, 'bar_attribute', 'bar_value')
class BarClass(object):
foo_attribute = FooDescriptor(owner=BarClass)
Is it possible to access the 'owner' class inside a descriptor during the __init__
function of that descriptor, without passing it in manually as in this example?
class FooDescriptor(object):
def __init__(self, owner):
#do things to owner here
setattr(owner, 'bar_attribute', 'bar_value')
class BarClass(object):
foo_attribute = FooDescriptor(owner=BarClass)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行此类操作的一种方法是使用元类。只要确保它确实是你想要的,如果你不明白它是如何工作的,不要盲目复制。
如果您需要传递其他参数,您可以使用例如
(class, args)
的元组代替类,或者使FooDescriptor
成为一个装饰器,它将返回构造函数中只接受一个参数的类。One way to do something like that is with a metaclass. Just make sure it's really what you want, and don't just copy blindly if you don't understand how it works.
If you need to pass additional arguments, you could use e.g. a tuple of
(class, args)
in the place of the class, or makeFooDescriptor
a decorator that would return a class that takes only one argument in the ctor.从Python 3.6开始,您可以使用
__set_name__
特殊方法:在创建类后立即在类中的所有描述符上自动调用
__set_name__
。有关更多详细信息,请参阅 PEP 487。
Since Python 3.6, you can use the
__set_name__
special method:__set_name__
is automatically called on all descriptors in a class immediately after the class is created.See PEP 487 for more details.