Python学习总结( 六 )

可调用对象 , 像方法一样调用对象 。
1 class Entity: 2'''Class to represent an entity. Callable to update the entity's position.''' 34def __init__(self, size, x, y): 5self.x, self.y = x, y 6self.size = size 78def __call__(self, x, y): 9'''Change the position of the entity.'''10self.x, self.y = x, y11print(x, y)12 13 entity = Entity(5, 1, 1)14 entity(2, 2)资源管理
1 class Closer: 2def __enter__(self): 3return self 45def __exit__(self, exception_type, exception_val, trace): 6print("清理完成") 7return True; 89 with Closer() as closer:10pass对象描述符 。
1 class Meter(object): 2'''Descriptor for a meter.''' 34def __init__(self, value=http://kandian.youth.cn/index/0.0): 5self.value = float(value) 6def __get__(self, instance, owner): 7return self.value 8def __set__(self, instance, value): 9self.value = float(value)10 11 class Foot(object):12'''Descriptor for a foot.'''13 14def __get__(self, instance, owner):15return instance.meter * 3.280816def __set__(self, instance, value):17instance.meter = float(value) / 3.280818 19 class Distance(object):20'''Class to represent distance holding two descriptors for feet and21meters.'''22meter = Meter()23foot = Foot()Mixin(也叫掺入)掺入模块:playable.py
1 # coding=utf-82 3 def paly(self):4print("游戏中...")掺入目标模块:test.py
1 # coding=utf-82 3 class Animal:4from playable import paly5 6 animal = Animal()7 animal.paly() # 游戏中...Open Class(打开类型 , 从新定义成员) 1 #coding:utf-8 23 class TestClass: 4def method1(self): 5print("方法1") 67 def method2(self): 8print("方法2") 9 10 TestClass.method2 = method211 12 test = TestClass()13 test.method1() # 方法114 test.method2() # 方法2Meta Programming(元编程)1 TestClass = type("TestClass", (object,), {2"say": lambda self : print("你好啊")3 })4 5 test = TestClass()6 test.say() 1 def getter(name): 2def getterMethod(self): 3return self.__getattribute__(name) 4return getterMethod 56 def setter(name): 7def setterMethod(self, value): 8self.__setattr__(name, value) 9return setterMethod10 11 class TestClass:12getName = getter("name")13setName = setter("name")14 15 test = TestClass()16 test.setName("段光伟")17 print(test.getName())AOP(面向切面编程)内容比较多 , 单独写了一篇文章: 。
备注【Python学习总结】Python在作用域方面非常接近Javascript , 类型和对象系统也有几份相似(虽然Javascript是基于原型的) , Javascript、PHP、Python和Ruby这几门语言交叉学习会带来意想不到的收获 。


推荐阅读