首页 新闻 会员 周边

关于Python元类的一个问题。。。。

0
悬赏园豆:10 [待解决问题]

大家好,最近一段时候正在看Python的元类,但是有一个地方比较疑惑,问题如下:

class MyMetaClass(type):
def __init__(cls,cls_name,cls_bases,cls_dict):
print('-----------------------------')
"""
问题2:__init__好像就没有什么用,随便怎么写.
"""

def __new__(cls, cls_name,cls_bases,cls_dict):
obj = super().__new__(cls,cls_name,cls_bases,cls_dict)
for key,value in obj.__dict__.items():
print(key,value)
"""
问题1:在这里:__new__按道理来说只是创建一个空对象,Student,但是从结果来看,
__new__当中对对象已经初始化了,也就是将__init__的活给干了,这是为什么,难道说元类
__new__比较特殊吗??
__module__ __main__
__doc__ None
__weakref__ <attribute '__weakref__' of 'Student' objects>
teach <function Student.teach at 0x0000000002506378>
__dict__ <attribute '__dict__' of 'Student' objects>
__init__ <function Student.__init__ at 0x00000000025062F0>
country China
"""
return obj




class Student(object,metaclass=MyMetaClass):

country = 'China'

def __init__(self,name,age):
self.name = name
self.age = age

def teach(self):
pass
数据分析玩家的主页 数据分析玩家 | 初学一级 | 园豆:192
提问于:2018-08-13 18:20
< >
分享
所有回答(1)
0

可以这样理解,对象是类的实例,类是元类的实例,

init方法是用来初始化实例的,new方法是用来创建实例的,

Uteki | 园豆:573 (小虾三级) | 2018-08-13 19:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册