Python类__getattribute__函数

Python类__getattribute__函数教程

每一个 Python 中的 实例对象 中,都有一个内置的 __getattribute__ 函数,当我们访问一个不管是存在还是不存在的 实例属性 时,就会自动调用到 __getattribute__ 函数。

如果,我们使用类名访问一个不管存在还是不存在的 类属性,那么是不会调用 __getattribute__ 函数的。如果,程序中同时有 __getattribute__ 方法和 __getattr__ 方法,那么首先调用 __getattribute__ 方法。

Python类__getattribute__函数详解

语法

def __getattribute__(self, item): pass

说明

当我们访问一个实例属性时,会自动调用 __getattribute__ 函数,其中 item 参数是我们访问的属性。

案例

访问不存在的类属性

访问不存在的类属性,不会自动调用 __getattribute__ 方法

print("嗨客网(www.haicoder.net)") class Student: course = "Python" def __getattribute__(self, item): print("get key =", item) print("Student course =", Student.course) print("Student name =", Student.name)

程序运行后,控制台输出如下:

49_python类getattribute函数.png

为 Student 类添加了一个类属性和一个 __getattribute__ 函数,此时我们使用类名访问了一个存在的类属性 course 和一个不存在的类属性 name,程序报错,并没有调用到 __getattribute__ 函数。

访问实例属性

访问实例属性,会自动调用 __getattribute__ 方法

print("嗨客网(www.haicoder.net)") class Student: course = "Python" def __init__(self, name, age): self.name = name self.age = age def __getattribute__(self, item): print("get key =", item) stu = Student("William", 18) print("stu name =", stu.name, "age =", stu.age) print("stu score =", stu.score)

程序运行后,控制台输出如下:

50_python类getattribute函数.png

我们创建了一个类 Student,并且为该类添加了一个类属性 course 和两个实例属性 name 和 age,以及一个 __getattribute__ 方法。

接着,我们创建了一个 Student 的实例 stu,并且使用 stu 实例访问了两个存在的属性 name 和 age,一个不存在的属性 score,结果我们发现程序调用了三次 __getattribute__ 函数。

即,不管,我们访问存在的属性还是不存在的属性,都会调用到 __getattribute__ 函数,而且,我们原来设置的 name 和 age 属性的值,都变成了 None,这是因为 __getattribute__ 函数没有返回任何值。我们再次将程序修改如下:

print("嗨客网(www.haicoder.net)") class Student: course = "Python" def __init__(self, name, age): self.name = name self.age = age def __getattribute__(self, item): return "HaiCoder" stu = Student("William", 18) print("stu name =", stu.name, "age =", stu.age) print("stu score =", stu.score)

程序运行后,控制台输出如下:

51_python类getattribute函数.png

我们给 __getattribute__ 方法返回了 “HaiCoder”,所以此时,所有的属性的值都变成了 “HaiCoder”。

访问实例属性

如果同时有 __getattribute__ 方法和 __getattr__ 方法,首先调用 __getattribute__ 方法

print("嗨客网(www.haicoder.net)") class Student: course = "Python" def __init__(self, name, age): self.name = name self.age = age def __getattribute__(self, item): print("get attribute =", item) return "HaiCoder" def __getattr__(self, item): print("get attr =", item) return "HaiCoder2" stu = Student("William", 18) print("stu name =", stu.name, "age =", stu.age) print("stu score =", stu.score)

程序运行后,控制台输出如下:

52_python类getattribute函数.png

Stduent 类中,同时有 __getattribute__ 方法和 __getattr__ 方法,我们看到程序首先调用了 __getattribute__ 方法。

Python类__getattribute__函数总结

每一个 Python 中的实例对象中,都有一个内置的 __getattribute__ 函数,当我们访问一个不管是存在还是不存在的实例属性时,就会自动调用到 __getattribute__ 函数。

如果,我们使用类名访问一个不管存在还是不存在的类属性,那么是不会调用 __getattribute__ 函数的。如果,程序中同时有 __getattribute__ 方法和 __getattr__ 方法,那么首先调用 __getattribute__ 方法。