面向对象

  • 面向对象分析(object oriented analysis, OOA)
  • 面向对象设计(object oriented dsign, OOD)
  • 面向对象编程(object oriented programmming, OOP)
  • 面向对象测试(object oriented test, OOT)
  • 面向对象维护(object oriented maintenance, OOSM)

类和对象

  1. class Person:

继承

  1. class A:
  2. pass
  3. class B(A):
  4. pass

抽象类

模块:abc
被装饰器修饰的方法,子类必须重写该方法

  1. import abc
  2. class Animal(metaclass=abc.ABCMeta):
  3. @abc.abstractmethod
  4. def walk(self):
  5. pass
  6. @abc.abstractmethod
  7. def say(self):
  8. pass
  9. # class Person(Animal):
  10. # pass
  11. # p1 = Person() # 异常
  12. class Person(Animal):
  13. def walk(self):
  14. print('站着走路')
  15. def say(self):
  16. print('说普通话')
  17. p1 = Person()
  18. p1.say()

isinstance issubclass

反射

  1. hasattr()
  2. getattr()
  3. setattr()
  4. delattr()

内置

__setattr__,__getattr__,delattr__

  1. class Person:
  2. def __init__(self, name):
  3. self.name = name
  4. def __setattr__(self, key, value):
  5. pass
  6. def __delattr(self, key):
  7. pass
  8. def __getattr(self, key):
  9. pass
  10. p = Person('lishi')
  11. p.name = 'zhangsan' # 设置属性时触发__setattr__
  12. def p.name # 触发__delattr__
  13. print(p.name) # 不触发__getattr__
  14. # 属性不存在时,触发__getattr__()方法
  15. print(p.age) # 触发__getattr__

__getitem__ __setitem__ __delitem__

  1. class Foo:
  2. pass
  3. f = Foo()
  4. f[key] = 1 # 调用 __setitem__()
  5. print(f[key]) # __getitem__()
  6. del f[key] # __delitem__()

__slots__

  1. class People:
  2. __slots__ = ['x'] # 只能有x属性
  3. p = People()
  4. p.y = 2 # 报错
  5. # 由这个类产生的对象只能有__slots__中的属性,这个对象没有__dict__属性

__next__ __iter__

  1. # 可迭代协议

__doc__

__module__ __class__

__del__

对象被删除时

__enter__``__exit__

  1. # 上下文管理协议
  2. with open('a.txt', 'w') as f:
  3. pass
  4. class Foo:
  5. def __enter__()
  6. with是触发 __enter__ 方法
  7. with子代码块执行结束后 触发 __exit__方法
  8. return True 忽略异常

__call__

  1. class Foo:
  2. def __call__(self, *args, **kwargs):
  3. pass
  4. f = Foo()
  5. f() # 调用__call__()

()执行时调用

元类

  1. # type ---> 类 ---> 对象
  2. # type() 创建类
  3. def test(self):
  4. print('test function')
  5. class_name = 'Foo'
  6. bases = ()
  7. class_dic = {
  8. 'x': 1,
  9. 'run': test
  10. }
  11. Foo = type(class_name, bases, class_dic)
  12. f = Foo()
  13. print(f.x) # 1
  14. f.run() # test function