type构建类
def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
"""
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
# (copied from class doc)
"""
pass
type(object) -> the object's type
,返回对象的类型,例如type(10)type(name,bases,dict) -> a new type
返回一个新的类型
XClass = type("myclass",(object,),{"a":100,"b":"string"}) # 字典是类属性
print(XClass)
print(XClass.__dict__)
print(XClass.__name__)
print(XClass.__bases__)
print(XClass.mro())
def init(self):
self.x = 1000
def show(self):
print("我是实例方法",self.__dict__)
@classmethod
def show1(cls):
print("类方法",cls)
XClass = type("myclass",(object,),{"a":100,"b":"string",
"show1":show1,"show":show,"__init__":init})
print(XClass)
print(XClass.__name__)
print(XClass.__dict__)
print(XClass.mro())
print("- "*30)
# 使用类方法
XClass.show1()
# 使用实例方法
xclass = XClass()
xclass.show()
print(xclass.x)
__new__
方法类创建该类。metaclass = type
可以在类的继承体系括号中添加该参数为类指定该元类class Mode(type):
def __new__(cls,*args,**kwargs):
print(cls)
print(args)
print(kwargs)
print()
return super().__new__(cls,*args,**kwargs) #调用父类方法构建实例
class A(metaclass=Mode): #改变A类的元类,默认元类是type
id = 1000
def __init__(self):
print("A.init--------------")
# 第二种 B继承A后,元类依然是A中所指定的元类
class B(A):
def __init__(self):
print("B.init~~~~~~~~~~~")
# 第三种,元类可以使用下面的方式创建新的类
C = Mode("C",(),{})
# D、E是type的实例
class D:pass #等价于 D = type("D",(),{})
E = type("E",(),{})
class F(Mode):pass
print("= "*40)
print(type(A),A.__bases__)
print(type(B),B.__bases__)
print(type(C),C.__bases__)
print()
print(type(D),D.__bases__)
print(type(E),E.__bases__)
print()
print(type(F),F.__bases__)
__new__(cls,*args,**kwargs)
的参数解构。中间是一个元组('A', (), {'__module__': '__main__', '__qualname__': 'A', 'id': 1000, '__init__': })
对应(name,bases,dict)
class Mode(type):
def __new__(cls,name,bases,dt:dict):
print(cls)
print(name)
print(bases)
print(dt,"--------")
return super().__new__(cls,name,bases,dt) #调用父类方法构建实例
__new__
方法。class Column:
def __init__(self,fieldname=None,pk=False,nullable=False):
self.fieldname = fieldname
self.pk = pk
self.nullable = nullable
def __repr__(self):
return "<{} {}>".format(__class__.__name__,self.fieldname)
class ModelMeta(type):
def __new__(cls,name,bases,attrs:dict):
print(name,bases,attrs)
if "__tablename__" not in attrs:
attrs["__tablename__"] = str.lower(name)
primarykeys = []
# 为类动态绑定属性
for k,v in attrs.items():
if isinstance(v,Column):
if v.fieldname is None or v.fieldname.strip() == "":
v.fieldname = k #指段没有名字使用属性名
if v.pk:
primarykeys.append(v)
attrs["__primarykeys__"] = primarykeys
return super().__new__(cls,name,bases,attrs)
class Base(metaclass=ModelMeta):
"""继承Base的类的元类都是ModelMety"""
pass
class Student(Base):
id = Column(pk=True,nullable=False)
name = Column("username",nullable=False)
ags = Column()
print("- "*30)
print(Student.__dict__)
__new__()
方法中,可以获取元类信息、当前类、基类、类属性字典。