前言
python在调用类函数时其对象属性查找 ‘.’ 与进行函数调用 ‘()’ 是两个过程:
a=class.method()
等价于:
a=class.method; a=a()
那么python属性查找是一个怎样的过程呢?
分析
先了解一下dir()函数:
dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
我们通过dir来查看类以及类实例中包含了哪些方法,参数:
class aa():
def __init__(self):
name = 'test'
def print_test(self):
return 'aa'
b = aa()
print(dir(aa))
print(dir(b))
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'print_test']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'print_test']
其中__dict__就是存放变量属性方法的一个字典,我们可以打印出来看看:
print(aa.__dict__) print(b.__dict__)
{'__module__': '__main__', '__init__': <function aa.__init__ at 0x10adf15e0>, 'print_test': <function aa.print_test at 0x11c85a550>, '__dict__': <attribute '__dict__' of 'aa' objects>, '__weakref__': <attribute '__weakref__' of 'aa' objects>, '__doc__': None}
{}
python的(.)通过__getattribute__函数对实例与类变量的dict依次进行查询,若不存在则通过__getattr__函数返回错误信息。
附加
绑定方法与非绑定方法
绑定方法:封装了一个函数和一个类实例,可直接调用
非绑定方法:封装了方法函数的可调用对象 ,需要传入一个实例进行调用。
class a():
#
b=a()
meth = b.method #绑定方法
umeth = a.method #非绑定方法
meth()
umeth(b)#添加实例进行调用