class Animal:
def speak(self):
print('动物叫')
class Mammal(Animal):
def speak(self):
print('哺乳动物叫')
class Dog(Mammal):
def speak(self):
super().speak()
print('狗叫')
d = Dog()
d.speak()
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__)
class Engine:
def start(self):
print('发动机启动')
class Car:
def __init__(self):
self.engine = Engine() # 组合
def drive(self):
self.engine.start()
print('汽车行驶')
car = Car()
car.drive()
class Cat:
def speak(self):
print('喵喵!')
def animal_speak(animal):
animal.speak()
for a in [Dog(), Cat()]:
animal_speak(a)
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
# s = Shape() # TypeError: Can't instantiate abstract class
print(isinstance(Rectangle(1,2), Shape))
class Account:
def __init__(self, owner):
self.owner = owner
@classmethod
def create(cls, owner):
return cls(owner)
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
class Math:
@staticmethod
def add(a, b):
return a + b
print(Math.add(3, 5))
class MyList:
def __init__(self):
self.data = []
def __getitem__(self, idx):
return self.data[idx]
def __setitem__(self, idx, value):
self.data[idx] = value
def __len__(self):
return len(self.data)
def __iter__(self):
return iter(self.data)
def __contains__(self, item):
return item in self.data
def append(self, value):
self.data.append(value)
lst = MyList()
lst.append(10)
lst.append(20)
print(lst[0], len(lst), 10 in lst)
for x in lst:
print(x)
class ReadOnlyList:
def __init__(self, data):
self._data = list(data)
def __getitem__(self, idx):
return self._data[idx]
def __len__(self):
return len(self._data)
def __setitem__(self, idx, value):
raise TypeError('只读容器不允许修改')
rol = ReadOnlyList([1,2,3])
print(rol[0], len(rol))
# rol[0] = 10 # TypeError
class Fib:
def __init__(self, n):
self.n = n
def __iter__(self):
self.a, self.b, self.count = 0, 1, 0
return self
def __next__(self):
if self.count < self.n:
val = self.a
self.a, self.b = self.b, self.a + self.b
self.count += 1
return val
else:
raise StopIteration
for x in Fib(5):
print(x)
class PluginBase(ABC):
@abstractmethod
def run(self): pass
class PluginA(PluginBase):
def run(self): print('A插件')
class PluginB(PluginBase):
def run(self): print('B插件')
plugins = [PluginA(), PluginB()]
for p in plugins:
p.run()
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key in self.cache:
self.cache.move_to_end(key)
return self.cache[key]
return -1
def put(self, key, value):
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
lru = LRUCache(2)
lru.put('a', 1)
lru.put('b', 2)
lru.get('a')
lru.put('c', 3)
print(list(lru.cache.items()))
# MRO调试
print(Dog.__mro__)
# __repr__调试
class Demo:
def __repr__(self):
return ''
print(Demo())
实现一个插件系统,支持注册多种插件类,统一调用接口,动态扩展功能。
实现一个自定义容器类,支持下标、切片、for循环、只读、缓存等特性,并与内置list对比。
实现工厂、单例、装饰器等常见OOP设计模式的Python代码示例。
用UML类图工具画出你的类结构,并分析其高内聚、低耦合特性。