# 多继承顺序
super () 会沿着 __mro__
顺序调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class D: pass
class E: pass
class B(D): pass
class C(E): pass
class A(B, C): pass
print(A.__mro__)
class D: pass
class B(D): pass
class C(D): pass
class A(B, C): pass
print(A.__mro__)
|
# abstract class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import abc
class BaseCache(metaclass=abc.ABCMeta):
@abc.abstractmethod def get(self, key): pass
class RedisCache(BaseCache): pass
class BaseCache2: def get(self, key): raise NotImplementedError
class RedisCache2(BaseCache2): pass
redis_cache2 = RedisCache2()
redis_cache2.get('name')
|
# new & init
new 用来控制对象的生成过程,在对象生成之前,init 用来完善对象,如果 new 方法不返回对象不会调用 init
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class User:
def __new__(cls, *args, **kwargs): print('__new__') return super().__new__(cls)
def __init__(self, name): print('__init__')
u = User('babb')
class User:
def __new__(cls, *args, **kwargs): print('__new__') print('args: ', args) print('kwargs: ', kwargs)
def __init__(self, name): print('__init__')
u = User('babb')
u = User(name='babb')
|
# type
type 可以用来创建类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def say(self): print(f'i am {self.name}')
class BaseClass:
def hello(self): print('hello world')
User = type('User', (BaseClass, ), {'name': 'babb', 'say': say}) u = User() print(u.__dict__, User.__dict__, u.name) u.say() u.hello()
|
python 类实例化时会首先寻找 metaclass, 通过 metaclass 创建类,元类是用来创建类的类,需要继承 type,因为 type 可以用来创建类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class MetaClass(type): def __new__(cls, *args, **kwargs): print('meta __new__') return super().__new__(cls, *args, **kwargs)
class User(metaclass=MetaClass):
def __init__(self, name): self.name = name
def __str__(self): return 'user'
u = User('babb') print(u)
|