面向对象
- 面向对象分析(object oriented analysis, OOA)
- 面向对象设计(object oriented dsign, OOD)
- 面向对象编程(object oriented programmming, OOP)
- 面向对象测试(object oriented test, OOT)
- 面向对象维护(object oriented maintenance, OOSM)
类和对象
class Person:
继承
class A:passclass B(A):pass
抽象类
模块:abc
被装饰器修饰的方法,子类必须重写该方法
import abcclass Animal(metaclass=abc.ABCMeta):@abc.abstractmethoddef walk(self):pass@abc.abstractmethoddef say(self):pass# class Person(Animal):# pass# p1 = Person() # 异常class Person(Animal):def walk(self):print('站着走路')def say(self):print('说普通话')p1 = Person()p1.say()
isinstance issubclass
反射
hasattr()getattr()setattr()delattr()
内置
__setattr__,__getattr__,delattr__
class Person:def __init__(self, name):self.name = namedef __setattr__(self, key, value):passdef __delattr(self, key):passdef __getattr(self, key):passp = Person('lishi')p.name = 'zhangsan' # 设置属性时触发__setattr__def p.name # 触发__delattr__print(p.name) # 不触发__getattr__# 属性不存在时,触发__getattr__()方法print(p.age) # 触发__getattr__
__getitem__ __setitem__ __delitem__
class Foo:passf = Foo()f[key] = 1 # 调用 __setitem__()print(f[key]) # __getitem__()del f[key] # __delitem__()
__slots__
class People:__slots__ = ['x'] # 只能有x属性p = People()p.y = 2 # 报错# 由这个类产生的对象只能有__slots__中的属性,这个对象没有__dict__属性
__next__ __iter__
# 可迭代协议
__doc__
__module__ __class__
__del__
对象被删除时
__enter__``__exit__
# 上下文管理协议with open('a.txt', 'w') as f:passclass Foo:def __enter__()with是触发 __enter__ 方法with子代码块执行结束后 触发 __exit__方法return True 时 忽略异常
__call__
class Foo:def __call__(self, *args, **kwargs):passf = Foo()f() # 调用__call__()
()执行时调用
元类
# type ---> 类 ---> 对象# type() 创建类def test(self):print('test function')class_name = 'Foo'bases = ()class_dic = {'x': 1,'run': test}Foo = type(class_name, bases, class_dic)f = Foo()print(f.x) # 1f.run() # test function
