一、python中类
1.元类
2.根类
3.抽象类
4.空类
5.基本类
6.父类,子类
二、python之元类
1.python元类是类的类,其母的是用于动态的创建和控制类对象。
2.python的元类是非必要不要去使用。
3.type本质上是元类
4.元类创建类,类创建对象
5.python中多有的类本身是对象,默认元类为type
6.可以通过type函数动态创建类对象
7.元类是python的高级特性
8.python的元类是用于解决特定类型的问题,比如框架设计,插件系统等。
9.单例模式通过元类的call方法控制实例创建
10.接口协议
11.metaclass元类,class of class
12.所有类的默认元类为type
13.metaclass元类通过重写__new__和__init__等方法指定类的生产过程
三、类的核心方法
1.__prepare__(cls, name, bases, **kwargs)
2.__new__(mcs, name, bases, namespace)
3.__init__(cls, name, bases, namespace)
4.__call__(cls, *args, **kwargs)
四、metaclass元类的应用
1.自动注册子类
2.强制接口实现
3.ORM字段控制
案例一:type 就是 Python 中的默认元类
class Person:
def __init__(self,name):
self.name = name
def greet(self):
return f"hello,i'm {self.name}"
#创建一个实例
p = Person("Alice")
print(p.greet())
print(type(10)) #10的类型是:<class 'int'>
print(type(p)) #p的类型是:<class '__main__.Person'>
print(type(Person)) #Person的类型是:<class 'type'>

189

被折叠的 条评论
为什么被折叠?



