Home >Backend Development >Python Tutorial >How Do Python Descriptors\' `__get__` and `__set__` Methods Work?

How Do Python Descriptors\' `__get__` and `__set__` Methods Work?

DDD
DDDOriginal
2024-11-26 15:57:13920browse

How Do Python Descriptors' `__get__` and `__set__` Methods Work?

Understanding Python Descriptors: get and set

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:

  • instance: When accessing an attribute, this parameter represents the instance of the class that owns the descriptor (e.g., temp in temp.celsius).
  • owner: This parameter indicates the class that defines the descriptor (e.g., Temperature).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn