理解 __get__ 和 __set__ 以及 Python 描述符 [英] Understanding __get__ and __set__ and Python descriptors
问题描述
我试图了解 Python 的描述符是什么以及它们的用途.我了解它们的工作原理,但这是我的疑虑.考虑以下代码:
I am trying to understand what Python's descriptors are and what they are useful for. I understand how they work, but here are my doubts. Consider the following code:
class Celsius(object):
def __init__(self, value=0.0):
self.value = float(value)
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
self.value = float(value)
class Temperature(object):
celsius = Celsius()
为什么我需要描述符类?
Why do I need the descriptor class?
这里的 instance
和 owner
是什么?(在 __get__
中).这些参数的用途是什么?
What is instance
and owner
here? (in __get__
). What is the purpose of these parameters?
我将如何调用/使用此示例?
How would I call/use this example?
推荐答案
描述符是 Python 的 property
类型的实现方式.一个描述符简单地实现了 __get__
、__set__
等,然后在它的定义中添加到另一个类(就像上面对 Temperature 类所做的那样).例如:
The descriptor is how Python's property
type is implemented. A descriptor simply implements __get__
, __set__
, etc. and is then added to another class in its definition (as you did above with the Temperature class). For example:
temp=Temperature()
temp.celsius #calls celsius.__get__
访问您分配描述符的属性(在上面的示例中为celsius
)调用适当的描述符方法.
Accessing the property you assigned the descriptor to (celsius
in the above example) calls the appropriate descriptor method.
instance
是类的实例(所以上面的 __get__
会收到 temp
,而owner
是具有描述符的类(所以它是 Temperature
).
instance
in __get__
is the instance of the class (so above, __get__
would receive temp
, while owner
is the class with the descriptor (so it would be Temperature
).
您需要使用描述符类来封装为其提供动力的逻辑.这样,如果描述符用于缓存一些昂贵的操作(例如),它可以将值存储在它自己而不是它的类上.
You need to use a descriptor class to encapsulate the logic that powers it. That way, if the descriptor is used to cache some expensive operation (for example), it could store the value on itself and not its class.
可以在此处找到有关描述符的文章.
正如 jchl 在评论中指出的那样,如果您只是尝试 Temperature.celsius
,instance
将是 None
.
As jchl pointed out in the comments, if you simply try Temperature.celsius
, instance
will be None
.
这篇关于理解 __get__ 和 __set__ 以及 Python 描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!