type is actually a meta class, and type is the meta-class that creates all the objects behind Python rules for creating classes in Python:Suppose the class Foo is created
class Foo (Bar): def __init__ (): Pass
- Is there a __metaclass__ attribute in foo? If so, Python creates a class object named Foo in memory through __metaclass__, which is a class, but the class itself is an object, and a Python file module belongs to an Object.
- If Python does not find __metaclass__, it will continue to look for the __metaclass__ attribute in bar (parent Class) and try to do the same thing as Before.
- If Python cannot find __metaclass__ in any parent class, it will look for __metaclass__ in the module hierarchy and try to do the Same.
- If you still can't find __metaclass__,python, you'll use the built-in type to create this class Object.
Purpose: The main purpose of the Meta-class is to automatically change the class when the class is Created.The primary purpose of the Meta-class is to create an api. A typical example is the Django ORM. It allows you to define like This:the Flask SQLAlchemy ORM class is defined by inheriting a class base that is created, and note that all of the table classes in SQLAlchemy must inherit a base object, otherwise the base table created after the inheritance will not implement the ORM mapping;SQLAlchemy instances:
fromSqlalchemy.ext.declarativeImportDeclarative_basebase=declarative_base ()classHotwordtype (Base):#Table name __tablename__='Hotwordtype' #ID typeNameid = Column (Integer, primary_key=true)#PRIMARY KeyTypeName = Column (String (), nullable=false)#type nameHotword = Relationship ('Hotword', backref='Hotwordtype')
Declarative_base in the Meta-class source code:
The new baseclassWould be given a metaclass that producesappropriate:class: ' ~sqlalchemy.schema.table ' objects andmakesthe appropriate:func: '~Sqlalchemy.orm.mapper ' calls based on theinformation provided declarativelyinchTheclass andany subclassesof theclass.classDeclarativemeta (type):def __init__(cls, classname, bases, dict_):if '_decl_class_registry' not inchCls.__dict__: _as_declarative (cls, classname, cls.__dict__) Type.__init__(cls, classname, bases, dict_)def __setattr__(cls, key, value): _add_attribute (cls, key, Value)
Python Learning note 1-meta class __metaclass__