Fundamentals 5 min read

Python Property Access and Descriptor Magic Methods

This article explains Python's property access protocols and descriptor mechanisms, demonstrating how to customize attribute behavior using special methods like __getattribute__ and __getattr__.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Property Access and Descriptor Magic Methods

属性访问和描述符是Python中的重要概念,它们通过魔术方法(特殊方法)来定义对象的属性访问行为。属性访问协议定义了对象属性的获取、设置和删除操作,而描述符协议定义了自定义属性访问行为的方式。

属性访问协议包括以下魔术方法:

`__getattribute__(self, name)` : 当访问对象的属性时被调用。

`__getattr__(self, name)` : 当访问对象的不存在的属性时被调用。

`__setattr__(self, name, value)` : 当给对象的属性赋值时被调用。

`__delattr__(self, name)` : 当删除对象的属性时被调用。

描述符协议包括以下魔术方法:

`__get__(self, instance, owner)` : 当从描述符所属的类或实例中获取属性时被调用。

`__set__(self, instance, value)` : 当向描述符所属的类或实例中设置属性时被调用。

`__delete__(self, instance)` : 当从描述符所属的类或实例中删除属性时被调用。

下面是10个实用的场景代码,演示了如何使用属性访问和描述符来自定义对象的属性访问行为:

class MyClass:</code><code>    def __getattr__(self, name):</code><code>        if name == 'x':</code><code>            return 0</code><code>        raise AttributeError(f"'MyClass' object has no attribute '{name}'")</code><code>obj = MyClass()</code><code>print(obj.x)  # 输出: 0</code><code>print(obj.y)  # 抛出AttributeError异常

这些场景代码展示了如何使用属性访问和描述符来自定义对象的属性访问行为。通过实现相应的魔术方法和使用描述符,我们可以灵活地控制对象属性的获取、设置和删除操作,以及实现各种自定义的属性访问行为。

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonOOPPropertyDescriptor
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.