In Python, descriptors are a powerful mechanism that allow objects to intercept attribute access and modification. To grasp their functionality, let's delve into the provided code:
class Celsius(object): def __init__(self, value=0.0): self.value = value def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value) class Temperature(object): celsius = Celsius()
Q1: Why do I need a descriptor class?
A1: A descriptor class encapsulates the logic behind intercepting attribute access and modification. By separating this logic from the class using it, you can reuse it and provide a consistent interface for accessing and modifying attributes.
Q2: What are instance and owner in __get__?
A2:
Q3: How would I call/use this example?
A3: You can access and modify the celsius attribute as follows:
temp = Temperature() temp.celsius # calls `celsius.__get__` and returns the current Celsius value temp.celsius = 25.0 # calls `celsius.__set__` to update the Celsius value
Note: If you try to access Temperature.celsius directly, instance will be None.
The above is the detailed content of How Do Python Descriptors\' `__get__` and `__set__` Methods Work?. For more information, please follow other related articles on the PHP Chinese website!