-
多继承:
python支持,但不建议使用
dir(): 获取类或者对象的方法和属性
__mro__:获取类的继承顺序
class A(object): def run(self): print('run A run') class B(A): def run(self): super().run() print('run B run') class C(A): def run(self): super().run() print('run C run') class D(B, C): pass c = C() c.run() # 获取类或者对象的方法和属性 print(dir(C)) # 获取类的继承顺序 print(C.__mro__) d = D() d.run() print(D.__mro__)
- python魔法方法
class Student(object): def __init__(self, name = 'python'): self.__name = name def __str__(self): '''打印本类对象时,自动调用''' return 'hello, %s' % self.__name def __repr__(self): '''在解释器环境下直接输出本对象,自动调用的方法''' return self.__str__() def __len__(self): '''调用len函数的时候自动调用的方法''' return 100 def __call__(self): '''调用本类对象的时候自动调用的方法''' print('Student object name:%s' % self.__name) print(dir(Student)) s = Student() print(s) print(len(s)) s()
class Fib(object): cnt = 0 def __init__(self): self.a = 0 self.b = 1 def __iter__(self): '''返回可迭代对象''' return self def __next__(self): '''随着循环自动调用的''' self.a, self.b = self.b, self.a+self.b if self.a >= 100: '''循环遍历终止''' raise StopIteration() Fib.cnt += 1 return self.a def __len__(self): return Fib.cnt def __getitem__(self, n): '''索引时自动调用的方法''' if isinstance(n, int): a, b = 0, 1 while n >= 0: a, b = b, a+b n -= 1 return a if isinstance(n, slice): '''切片类型 start:end''' if n.start == None: start = 0 else: start = n.start if n.stop == None: return 'error' stop = n.stop l = [] for i in range(start, stop): l.append(self[i]) return l f = Fib() print(dir(f)) for i in f: print(i, end=' ') print() print(len(f)) for i in range(20): print(f[i], end=' ') print() print(f[0:3]) print(f[1:10])
- 枚举类
INSERT=1 # 缺点就是本质是变量,可以改变 if choose == INSERT: pass
from enum import Enum, unique @ unique # 防止枚举成员的重复 class Menu(Enum): INSERT=1 DELETE=2 UPDATE=3 SHOW=4 # CHOOSE=4 print(Menu.INSERT.value) # Menu.INSERT.value = 2 print(Menu['INSERT'])
- 元类(metaclass)
class Test(object): def show(self, name='python'): print('hello %s', name)
# type()构建一个类 def f(self, name='python'): print('hello %s'% name) Test = type('Test', (object,), dict(show=f)) t = Test() t.show() # 另一种构建类的方法,是先构建元类,以元类为模板构建类 class ListMetaclass(type): def __new__(cls, name, bases, attrs): '''类方法''' attrs['add'] = lambda self, value : self.append(value) return type.__new__(cls, name, bases, attrs) class Mylist(list, metaclass=ListMetaclass): pass l = Mylist() print(type(l)) l.add(1) l.add('hello') print(l)