2.面向对象一
本章内容:
- 类的用法
- 继承
- 接口与归一化设计
- 封装
- 类中方法
- 反射
一.类的用法:
1.实例化产生对象
2.属性的引用(数据属性|函数属性)
1.数据属性用的都是指向一个内存地址
2.函数属性分为方法和函数
方法会自动传入self,函数需要自己传入
二.继承

继承是基于抽象的结果
super().__init()#调用父类的__init__方法
注意:寻找继承关系需要从当前的位置往后找
三.接口与归一化设计
python3中都是新式类,广度优先

H->E->B->F->C->G->D->A
python2中有经典类,深度优先
H->E->B->A->F->C->G->D
四.封装
1.封装数据:保护隐私
2.封装方法:隔离复杂度
方式:在属性或者方法前面加一个"__"就可以隐藏起来了,供自己内部调用
五.(1)类中的方法(绑定方法)
绑定方法分为给类的方法和对象的绑定方法
如果没有任何装饰的方法都是绑定给对象的
绑定到类的方法需要加classmethod装饰
五.(2)类中的方法(非绑定方法)
加staticmethd非绑定方法,都可以使用
六.反射
通过字符串的形式操作对象相关的属性,常用配置三连,rsplit+importlib+反射
四个自省的函数
hasattr hasattr(object, name) getattr getattr(object, name, default=None) def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass setattr def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v'' """ pass delattr def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """ pass


浙公网安备 33010602011771号