Python 描述符

标签 python python-3.x python-descriptors

来自descriptor文档:

A descriptor can be called directly by its method name. For example, d.__get__(obj).

以下类的示例是什么?

class Descriptor:
    def __init__(self, color="red"):
        self.color = color

例如,什么是d,什么是obj"d.__get__(obj)" 将如何被上述类/实例调用?

最佳答案

工作示例

要使您的示例成为描述符,它需要有一个 __get__()方法:

class Descriptor:
    def __init__(self, color="red"):
        self.color = color
    def __get__(self, obj, objtype=None):
        return obj.size + ' ' + self.color

在另一个类中使用该描述符:

class A:
     pair = Descriptor('green')
     def __init__(self, size):
          self.size = size

像这样调用描述符:

>>> a = A('big')
>>> a.pair
'big green'

希望这个工作示例对您有所帮助:-)

要点

1) 类是一个 descriptor if 定义了 __get__()__set__() 或 __delete__() 中的任何一个。

2) 通过创建描述符的实例并将其作为类变量存储在另一个类中来使其工作。

3) 使用点运算符调用具有正常属性查找的描述符。

这就是它的全部:-)

关于Python 描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58478368/

相关文章:

python - 在后台更改 Windows 10 应用程序音频混合(最好使用 Python)

输入期间的 Python 操作()

python - 以声明方式设置类 __name__

python - 可作为实例方法调用?

json - 如何使用python3解析嵌套的json数据文件并将其插入sqlite数据库

python - 如何输入提示 python magic __get__ 方法

python - 如何在 TensorFlow 中添加正则化?

python - 如何使用代理服务器(如 luminati.io)正确地向 https 发出请求?

python - 选择与复选框的交互

python - 在 Nose 测试类中定义 Nose 测试方法