马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
__getattr__(self, name)
# 定义试图获取一个不存在的属性时的行为
__getattribute__(self, name)
# 定义该类的属性被访问时的行为
__setattr___(self, name, value)
# 定义一个熟悉被设置时的行为
__delattr__(self, name)
# 定义当一个熟悉被删除时的行为
练习1class Rectangle():
def __init__(self, width = 0, height = 0):
self.width = width
self.height = height
def __setattr__(self, name, value):
if name == 'squre':
self.width = value
self.height = value
else:
super().__setattr__(name, value)
# self.__dict__[name] = value
def getArea(self):
return self.width * self.height
r1 = Rectangle(4, 5)
r1.getArea
r1.squre = 10
r1.width
r1.height
测试题
0. 源代码def __setattr__(self, name, value):
self.name = value + 1
问题:导致无限递归了
解决方法:def __setattr__(self, name, value):
self.__dict__[name] = value + 1
或者:def __setattr__(self, name, value):
super().__setattr__(name, value + 1)
1. __getattribute__(self, name)
2. 打印3,2
3. 打印2,1
4. 问题:class Counter:
def __init__(self):
self.counter = 0 # 这里会触发 __setattr__ 调用
def __setattr__(self, name, value):
self.counter += 1
'''既然需要 __setattr__ 调用后才能真正设置 self.counter 的值,所以这时候 self.counter 还没有定义,所以没法 += 1,错误的根源。'''
super().__setattr__(name, value)
def __delattr__(self, name):
self.counter -= 1
super().__delattr__(name)
动动手
0 如注释class Demo:
def __getattr__(self, name):
'''当属性不存在时,不报错且提示“属性不存在”'''
return '属性不存在!'
1 实现功能class Demo:
def __getattr__(self, name):
self.name = 'FishC'
return self.name
2 编写类,实时检测对象有多少属性class Counter:
def __init__(self):
super().__setattr__('counter', 0)
def __setattr__(self, name, value):
super().__setattr__('counter', self.counter + 1)
def __delattr__(self, name):
super().__delattr__('counter', self.counter - 1)
|