python学习之面向对象学习进阶
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之面向对象学习进阶相关的知识,希望对你有一定的参考价值。
一、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.__age obj = Foo(20) print(obj.age) obj.age = 3 print(obj.age) del obj.age print(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 = 3 print(obj.age) del obj.age print(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 = 1 print(obj.__dict__) del obj.x print(obj.__dict__) obj.a = 1 obj.b = 2 print(obj.__dict__) del obj.a print(obj.__dict__) print(obj.aaaaaaaaa exec函数,将字符串中的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 self obj = 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(‘=>‘)
本文出自 “linux技术” 博客,请务必保留此出处http://haoyonghui.blog.51cto.com/4278020/1939924
以上是关于python学习之面向对象学习进阶的主要内容,如果未能解决你的问题,请参考以下文章