init 是用来完善实例的属性的
问题:new 到底是实例 还是 类?
A: new 是用来创建实例的 ; 但是类是元类的实例,所以new 能影响元类的实例--即是类的--的创建
程序运行class 语句时,就会创建类对象,建立存储地址;但是此时只建立了类对象,没有建立实例,就更加不会调用init;
因为init 接受的第一个参数就是 类的实例对象;只有执行实例化语句时才会调用init
__new__(cls, name, bases, attrs)方法接收到的参数依次是:
- 当前准备创建的类的对象;
- 类的名字;
- 类继承的父类集合;
- 类的方法集合。
# 元类
import numbers
class Field:
pass
class MetaClass(type):
def __new__(cls, name, bases, attrs, *args, **kwargs):
if name == "BaseClass":
return super().__new__(cls, name, bases, attrs, *args, **kwargs)
fields = {}
for key,value in attrs.items():
if isinstance(value, Field):
fields[key] = value
# else:
# try:
# raise ValueError("类对象不是继承Filed类")
# except:
# print("errror")
_Meta = {}
meta_table = getattr(attrs, "Meta", None)
db_table = name.lower()
if meta_table is not None:
table = meta_table["db_table"]
if table is not None:
db_table = table
_Meta["db_table"] = db_table
attrs["fields"] = fields
attrs["_Meta"] = _Meta
# del attrs["Meta"]
return super().__new__(cls,name, bases, attrs, *args, **kwargs)
class BaseClass(metaclass=MetaClass):
def __init__(self, *args, **kwargs):
for key,value in kwargs.items():
setattr(self,key,value)
return super(BaseClass, self).__init__()
class IntField(Field):
def __init__(self,db_colum,max_length,min_length):
self.db_colum = db_colum
self.max_length = max_length
self.min_length = min_length
self._value = None
if min_length > max_length:
raise ValueError("最小长度必须小于最大长度")
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
if isinstance(value,numbers.Integral):
self._value = value
else:
raise ValueError("输入值必须是int型")
class CharField(Field):
def __init__(self, db_colum, max_length, min_length):
self.db_colum = db_colum
self.max_length = max_length
self.min_length = min_length
self._value = None
if min_length > max_length:
raise ValueError("最小长度必须小于最大长度")
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
self._value = value
class User(BaseClass):
# 假如User机直接有元类创建,那就User创建实例时,就需要__init__,
# 解决方法就是不直接创建,而是先继承一个父类,这个父类是由metaclass创建的,把__init__写在父类中
# 子类的__init__ 会覆盖掉 父类的__init__ , 但是子类没有__init__的时候就会调用父类的 __init___
age = IntField(db_colum="age",max_length=10,min_length=0)
name = CharField(db_colum="name",max_length=100,min_length=0)
class Meta:
db_table = "user"
user = User(age=23,name="zhouhao")
user2 = User(age=11,name="zhou")
# 这样写的话,user实例的初始化会调用BaseClass的__init__
print(user.age)
print(user2.age)
11
11
程序执行顺序
1 由 type 创建MetaClass ,创建Filed;
但是有类使用BaseClass(metaclass=MetaClass):语句,于是MetaClass就成为BaseClass的元类了
2 扫描BaseClass 的语法,遇到init停止返回,语法扫描结束,调用 MetaClass 的 new 来创建BaseClass,
3 在new 中条件符合,直接super().__new__(cls, name, bases, attrs, *args, **kwargs) 其实就是用type创建BaseClass类
4 扫描IntField的语法,遇到init停止返回,语法扫描结束,调用父类(就是Field--也是一个)中的new 来创建IntField类,
5 同理创建CharField
6 扫描User的语法,遇到age , name 然后对应实例化;
7 继续扫描User语法,完成返回,调用父类的new ,但是父类没有,于是再往上找,找到父类的元类的new 来创建User类
问题:就是user和user2的age相互影响了
user <main.User object at 0x0000000004B90048>
fields= {'age': <main.IntField object at 0x0000000004B30DA0>, 'name': <main.CharField object at 0x0000000004B29C50>}
user2: <main.User object at 0x0000000004B29BE0>
fields={'age': <main.IntField object at 0x0000000004B30DA0>, 'name': <main.CharField object at 0x0000000004B29C50>}
在当前类(比如User)中查找定义的类的所有属性,如果找到一个Field属性,就把它保存到一个fields = {}中,同时从类属性中删除该Field属性,否则,容易造成运行时错误(实例的属性会遮盖类的同名属性);
for k in fields.keys():
attrs.pop(k)
# 元类
import numbers
class Field:
pass
class MetaClass(type):
def __new__(cls, name, bases, attrs, *args, **kwargs):
if name == "BaseClass":
return super().__new__(cls, name, bases, attrs, *args, **kwargs)
fields = {}
for key,value in attrs.items():
if isinstance(value, Field):
fields[key] = value
# else:
# try:
# raise ValueError("类对象不是继承Filed类")
# except:
# print("errror")
for k in fields.keys():
attrs.pop(k)
_Meta = {}
meta_table = getattr(attrs, "Meta", None)
db_table = name.lower()
if meta_table is not None:
table = meta_table["db_table"]
if table is not None:
db_table = table
_Meta["db_table"] = db_table
attrs["fields"] = fields
attrs["_Meta"] = _Meta
del attrs["Meta"]
return super().__new__(cls,name, bases, attrs, *args, **kwargs)
class BaseClass(metaclass=MetaClass):
def __init__(self, *args, **kwargs):
for key,value in kwargs.items():
setattr(self,key,value)
return super(BaseClass, self).__init__()
class IntField(Field):
def __init__(self,db_colum,max_length,min_length):
self.db_colum = db_colum
self.max_length = max_length
self.min_length = min_length
self._value = None
if min_length > max_length:
raise ValueError("最小长度必须小于最大长度")
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
if isinstance(value,numbers.Integral):
self._value = value
else:
raise ValueError("输入值必须是int型")
class CharField(Field):
def __init__(self, db_colum, max_length, min_length):
self.db_colum = db_colum
self.max_length = max_length
self.min_length = min_length
self._value = None
if min_length > max_length:
raise ValueError("最小长度必须小于最大长度")
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
self._value = value
class User(BaseClass):
# 假如User机直接有元类创建,那就User创建实例时,就需要__init__,
# 解决方法就是不直接创建,而是先继承一个父类,这个父类是由metaclass创建的,把__init__写在父类中
# 子类的__init__ 会覆盖掉 父类的__init__ , 但是子类没有__init__的时候就会调用父类的 __init___
age = IntField(db_colum="age",max_length=10,min_length=0)
name = CharField(db_colum="name",max_length=100,min_length=0)
class Meta:
db_table = "user"
if __name__ == "__main__":
user = User(age=23,name="zhouhao")
user2 = User(age=11,name="zhou")
# 这样写的话,user实例的初始化会调用BaseClass的__init__
print(user.age)
print(user2.age)
23
11
网友评论