如何将描述符用于非静态方法? [英] How can I use descriptors for non-static methods?

查看:31
本文介绍了如何将描述符用于非静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用描述符来更改静态属性,就好像它是普通属性一样.但是,当我尝试将描述符用于普通类属性时,我最终会更改它引用的对象,而不是对象中的值.

I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.

如果我有

正常使用,考虑method(param)返回一个对象

Normal use, considering that the method(param) returns an object

class SomeClass():
    property = method(param)

然后我可以这样做:

instance = SomeClass()
instance.property = 3

并且能够让该设置由哪个属性是实例的类来处理.

and be able to have that setting handled by the the class of which property is an instance.

现在,如果我有

class SomeClass():
    def__init__(self):
        self.property = method(param)

而我这样做:

instance = SomeClass()
instance.property = 3

该代码不起作用,我用 3 覆盖了对 method(param) 创建的对象的引用,而不是让描述符处理该设置.

That code does not work, and I overwrite the reference to the object created by method(param) with 3, instead of having that setting handled by the descriptor.

有没有办法在没有静态方法的情况下使用描述符?本质上,我需要能够创建类的多个实例,每个实例都有自己独特的属性,可以使用方便的描述符方法进行更改.这可能吗?

Is there a way I can use descriptors without static methods? In essence, I need to be able to create several instances of the class, each with its own unique properties that can be altered using the convenient descriptor method. Is that possible?

Python 版本:2.7

Python version: 2.7

谢谢!

推荐答案

考虑到 method(param) 返回一个描述符,您可以使用如下属性手动调用它:

Considering method(param) returns a descriptor, you may invoke it manually with a property like so:

class SomeClass(object):

    def __init__(self):
        self._descriptor = method(param)

    @property
    def my_attribute(self):
        return self._descriptor.__get__(self, self.__class__)

    @my_attribute.setter
    def my_attribute(self, value):
        self._descriptor.__set__(self, value)

这将允许您创建特定于实例的描述符而不是类级别的描述符.

This will allow you to create instance-specific descriptors instead of class-level descriptors.

我仍然不明白您这样做的原因,因为描述符通常应该是类级别的.这就是他们的观点.否则,它们只是您可以使用属性调用的常规对象.

I still do not see the reason for you to do that as descriptors should usuallty be class-level. That's their point. Else they are just regular objects which you can call using properties.

这篇关于如何将描述符用于非静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆