python基础十一——类的内置attr属性

class Feng:
    x = 1
    def __init__(self,y):
        self.y = y
    #调用一个不存在的属性会触发
    def __getattr__(self, item):
        print('执行__getattr__')
    #删除的时候都会触发
    def __delattr__(self, item):
        print('删除操作__delattr__')
    def __setattr__(self, key, value):
        print('__setattr__执行')
        #self.key = value#会进入无限递归
        self.__dict__[key]=value

f1 = Feng(10)
print(f1.y)
print(f1.x)
del f1.x
class Feng:
    def __init__(self,name):
        self.name = name
    #如果不写则系统默认帮你处理加到__dict__中
    def __getattr__(self, item):
        print('你找的属性不存在%s' %item)

    def __setattr__(self, key, value):
        print('执行setattr',key,value)
        if type(value) is str:
            print('setting')
           # self.key = value#此时会造成死循环
            self.__dict__[key] = value
        else:
            print('please to setting')
    def __delattr__(self, item):
      #  del self.item#造成死循环
        self.__dict__.pop(item)
        print('执行删除')
f1 = Feng('fengfeng')
f1.age = 18
f1.gender = 'nv'
print(f1.name)
print(f1.__dict__)
del f1.name

你可能感兴趣的:(python基础十一——类的内置attr属性)