一、property属性高级用法可以将对象方法作为属性使用例子:class Foo: def __init__(self, age): ) self.__age = age @property def age(self): return self.__age @age.setter def age(self, args): self.__age = args @age.deleter def age(self): del self.__ageobj = Foo(20)print(obj.age)obj.age = 3print(obj.age)del obj.ageprint(obj.age)class Foo: def __init__(self, age): self.__age = age def get_age(self): return self.__age def set_age(self, args): self.__age = args def del_age(self): del self.__age age = property(get_age, set_age, del_age)obj = Foo(20)print(obj.age)obj.age = 3print(obj.age)del obj.ageprint(obj.age)__str__方法,默认返回对象内存地址,可以修改重写默认方法例子:class Foo: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return 'name: %s, age: %s' %(self.name, self.age)obj = Foo('egon', '18')print(obj)__getitem__, __setitem__,__delitem__可以通过字典的方式调用属性和方法例子:class Foo: def __init__(self, name): self.name = name def __getitem__(self, item): print("getitem") return self.__dict__[item] def __setitem__(self, key, value): print("setitem", key, value) self.__dict__[key] = value def __delitem__(self, key): print('del obj[key]时,执行') self.__dict__.pop(key)obj = Foo('egon')print(obj.name)#obj.name = 'alex'#obj['name'] = 'alex'print(obj['name'])del obj['name']print(obj['name'])__call__回掉函数,可以将对象变成可调用的例子:class Foo: def __call__(self, *args, **kwargs): print('====>')obj = Foo()obj()__getattr__从对象中读取某个属性时,首先需要从self.__dicts__中搜索该属性,再从__getattr__中查找__setattr__用来设置对象的属性,通过object中的__setattr__函数来设置属性__delattr__用来删除对象的属性例子:class Foo: def __init__(self, x): self.x = x def __getattr__(self, item): print('getattr') def __setattr__(self, key, value): self.__dict__[key] = value def __delattr__(self, item): self.__dict__.pop(item)obj = Foo(10)obj.x = 1print(obj.__dict__)del obj.xprint(obj.__dict__)obj.a = 1obj.b = 2print(obj.__dict__)del obj.aprint(obj.__dict__)print(obj.aaaaaaaaaexec函数,将字符串中的python代码提取出来执行例子:s="print(x)"g={'x':100000000}l={'x':1}exec(s,g,l)s = "y=2"exec(s, g, l)print(g)print(l)
二、二次加工标准类
例子:
(): (itemtag=): ().(item) .tag=tag (p_object): (p_object): (%p_object) (List).append(p_object) (): mid_index=()//[mid_index] (): .tag: () ().clear() .tag=l=List([])(l)(l.mid)
实现迭代器协议例子:class Foo: def __init__(self, n, stop): self.n = n self.stop = stop def __next__(self): if self.n > self.stop: raise StopIteration x = self.n self.n += 1 return x def __iter__(self): return selfobj = Foo(0, 5)print(next(obj))print(next(obj))print(next(obj))实现上下文管理器:例子:class Foo: def __init__(self, name): self.name = name def __enter__(self): print('enter') return self def __exit__(self, exc_type, exc_val, exc_tb): print('exit')with Foo('alex') as x: print(x) print('=>') print('=>') print('=>')