属性访问

属性访问

getattr(self, name)
定义当用户试图获取一个不存在的属性时的行为
getattribute(self, name)
定义当该类的属性被访问肘的行为
setattr(self, name, value)
定义当一个属性被设置时的行为
delattr(self, name)
定义当一个属性被删除肘的行为 

class C:
def getattribute(self, name):
print(‘getattribute’)
return super().getattribute(name)
def getattr(self, name):
print(‘getattr’)
def setattr(self, name, value):
print(‘setattr’)
return super().setattr(name,value)
def delattr(self, name):
print(‘delattr’)
super().delattr(name)

c = C()
c.x
getattribute
getattr

class Rectangle:
def init(self,width = 0,height = 0):
self.width = width
self.height = height

def __setattr__(self, name, value):
    if name == 'suqare':
        self.width = value
        self.height = value
    else:
        self.name = value

def getArea(self):
    return self.width * self.height

c = Rectangle(4,5)
Traceback (most recent call last):
File “<pyshell#89>”, line 1, in
c = Rectangle(4,5)
File “C:/Users/Assam/Desktop/1113.py”, line 3, in init
self.width = width
File “C:/Users/Assam/Desktop/1113.py”, line 11, in setattr
self.name = value
File “C:/Users/Assam/Desktop/1113.py”, line 11, in setattr
self.name = value
File “C:/Users/Assam/Desktop/1113.py”, line 11, in setattr
self.name = value
[Previous line repeated 1019 more times]
File “C:/Users/Assam/Desktop/1113.py”, line 7, in setattr
if name == ‘suqare’:
RecursionError: maximum recursion depth exceeded in comparison

改进后

class Rectangle:
def init(self,width = 0,height = 0):
self.width = width
self.height = height

def __setattr__(self, name, value):
    if name == 'suqare':
        self.width = value
        self.height = value
    else:
        self.__dict__[name] = value

def getArea(self):
    return self.width * self.height

c = Rectangle(4,5)
c.getArea()
20

致清 wechat
微信扫描二维码,和我一起探讨学习!