youandme 2020-04-15
在 python 中,一切皆为对象,类其实也是对象,为什么这么说??类时通过调用元类产生的
元类就是用来实例化产生类的类,它的作用就是用来产生自定的类
关系:元类---->实例化------>类------>实例化------>对象(obj)
class People: def __init__(self, name, age): self.name = name self.age = age def say(self): print(‘%s:%s‘%(self.name, self.age)) # print(People.__dict__) #如何得到对象 # obj = 调用类() obj = People(‘egon‘, 18) print(type(obj)) #<class ‘__main__.People‘> #如果说类也是对象 # People = 调用类()
查看内置的元类:
1、type 是内置的元类
2、我们用 class 关键字定义的所有类以及内置的类都是由元类 type 实例化产生的
print(type(People)) #<class ‘type‘> print(type(int)) #<class ‘type‘> print(type(str)) #<class ‘type‘>
类有三大特征:
class_name = "People"
class_bases = (object,)
class_dic = {} #定义一个局部名称空间 class_body = """ def __init__(self, name, age): self.name = name self.age = age def say(self): print(‘%s:%s‘%(self.name, self.age)) """ exec(class_body, {}, class_dic) print(class_dic) #{‘__init__‘: <function __init__ at 0x108382e18>, ‘say‘: <function say at 0x108575378>}
补充:exec 的用法
#exec:三个参数 #参数一:包含一系列python代码的字符串 #参数二:全局作用域(字典形式),如果不指定,默认为globals() #参数三:局部作用域(字典形式),如果不指定,默认为locals() #可以把exec命令的执行当成是一个函数的执行,会将执行期间产生的名字存放于局部名称空间中 g={ ‘x‘:1, ‘y‘:2 } l={} exec(‘‘‘ global x,z x=100 z=200 m=300 ‘‘‘,g,l) print(g) #{‘x‘: 100, ‘y‘: 2,‘z‘:200,......} 全局名称空间 print(l) #{‘m‘: 300} 局部名称空间
People = type(class_name, class_bases, class_dic) print(People) #<class ‘__main__.People‘>
class Mymeta(type): #只有继承了 type 类的类才是元类 # def __init__(cls,*args, **kwargs): # print(args) #args = (class_name, class_bases, class_dic) def __init__(self, class_name, class_bases, class_dic): super().__init__(class_name, class_bases, class_dic) print(self) #<class ‘__main__.People‘> print(class_name) #People print(class_bases) #(<class ‘object‘>,) print(class_dic) #{‘__init__‘: <function __init__ at 0x10e3ade18>, ‘say‘: <function say at 0x10e5a0378>} if not class_name.istitle(): raise NameError(‘类名的首字母必须大写啊‘) #当前所在的类,调用类时所传入的参数 def __new__(cls, *args, **kwargs): #调用类产生新的空对象 #造 Mymeta的对象 print(‘__new__ run....‘) print(cls) #<class ‘__main__.Mymeta‘> print(args) #(‘People‘, (<class ‘object‘>,), {...}) print(kwargs) #{} # return super().__new__(cls, *args, **kwargs) return type.__new__(cls, *args, **kwargs) #<class ‘__main__.People‘> People = Mymeta(class_name,class_bases,class_dic) # 结果展示 ‘‘‘ 先自动调用__new__方法,产生空对象 __new__ run.... <class ‘__main__.Mymeta‘> (‘People‘, (<class ‘object‘>,), {‘__init__‘: <function __init__ at 0x10e3ade18>, ‘say‘: <function say at 0x10e5a0378>}) {} #然后再自动调用__init__方法,初始化对象 <class ‘__main__.People‘> People (<class ‘object‘>,) {‘__init__‘: <function __init__ at 0x10e3ade18>, ‘say‘: <function say at 0x10e5a0378>} ‘‘‘
调用 Mymeta 发生三件事,调用Myneta就是==> type.__ call __ ():
1、先造一个空对象==》People,调用Mymeta 类内的__ new __ 方法
2、调用 Mymeta这个类内的__ init __方法,完成初始化对象的操作
3、返回初始好的对象
自定义元类可以控制类的产生过程,类的产生过程其实就是元类的调用过程
People = Mymeta() ---> type.__ call __ ==>干了3件事
1、type.__ call __ 函数内会先调用 Mymeta内的 __ new__
2、type.__ call __ 函数内会再调用Mymetan内的 __ init__
3、type.__ call__函数内会返回一个初始化好的对象
# class People(metaclass=Mymeta): #===》People = Mymeta(‘类名‘, (object,), 类的名称空间) class People(metaclass=Mymeta): #===》People = Mymeta(‘People‘, (), {...}) def __init__(self, name, age): self.name = name self.age = age def say(self): print(‘%s:%s‘ % (self.name, self.age)) # 结果展示 ‘‘‘ __new__ run.... <class ‘__main__.Mymeta‘> (‘People‘, (), {‘__module__‘: ‘__main__‘, ‘__qualname__‘: ‘People‘, ‘__init__‘: <function People.__init__ at 0x101b71620>, ‘say‘: <function People.say at 0x101b716a8>}) {} <class ‘__main__.People‘> People () {‘__module__‘: ‘__main__‘, ‘__qualname__‘: ‘People‘, ‘__init__‘: <function People.__init__ at 0x101b71620>, ‘say‘: <function People.say at 0x101b716a8>} ‘‘‘
强调:
只要是调用类,那么会依次调用:
1、类内的__ new __
2、类内的__ init __
案例:
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类 def __init__(self,class_name,class_bases,class_dic): # print(self) #<class ‘__main__.StanfordTeacher‘> # print(class_bases) #(<class ‘object‘>,) # print(class_dic) #{‘__module__‘: ‘__main__‘, ‘__qualname__‘: ‘StanfordTeacher‘, ‘school‘: ‘Stanford‘, ‘__init__‘: <function StanfordTeacher.__init__ at 0x102b95ae8>, ‘say‘: <function StanfordTeacher.say at 0x10621c6a8>} super(Mymeta, self).__init__(class_name, class_bases, class_dic) # 重用父类的功能 if class_name.islower(): raise TypeError(‘类名%s请修改为驼峰体‘ %class_name) if ‘__doc__‘ not in class_dic or len(class_dic[‘__doc__‘].strip(‘ \n‘)) == 0: raise TypeError(‘类中必须有文档注释,并且文档注释不能为空‘) # StanfordTeacher=Mymeta(‘StanfordTeacher‘,(object),{...}) class StanfordTeacher(object,metaclass=Mymeta): """ 类StanfordTeacher的文档注释 """ school=‘Stanford‘ def __init__(self,name,age): self.name=name self.age=age def say(self): print(‘%s says welcome to the Stanford to learn Python‘ %self.name)
在该类内部添加 __ call __方法,可以实现对象( )的调用
对象() --->类的__ call __
类() ----->自定义元类内的__ call __
自定义元类() ---->内置元类(type)的__ call __
class Foo: def __init__(self,x,y): self.x = x self.y = y def __call__(self, *args, **kwargs): print(‘====>‘,args, kwargs) return "__call__ 触发了" obj = Foo(111, 222) # print(obj.__str__()) # <__main__.Foo object at 0x10223f898> 默认返回的是对象的内存地址 print(obj) # 等同于 obj.__str___ #应用: 对象加空号调用,需要在该对象的类中添加一个方法__call__ res = obj(1,2,3, a=4, b=5, c=6) #等同于 obj.__call__() print(res) #__call__ 触发了 # 结果展示: ‘‘‘ ====> (1, 2, 3) {‘a‘: 4, ‘b‘: 5, ‘c‘: 6} ‘‘‘ # 总结: ‘‘‘ 对象() --->类的__call__ 类() ----->自定义元类内的__call__ 自定义元类() ---->内置元类(type)的__call__ ‘‘‘
案例:我们可以通过改写__ call __的逻辑从而控制调用StanfordTeacher的过程,比如将StanfordTeacher的对象的所有属性都变成私有的
class Mymeta(type): #只有继承了type类才能称之为一个元类,否则就是一个普通的自定义类 def __call__(self, *args, **kwargs): #self=<class ‘__main__.StanfordTeacher‘> #1、调用__new__产生一个空对象obj obj=self.__new__(self) # 此处的self是类StanfordTeacher,必须传参,代表创建一个StanfordTeacher的对象obj #2、调用__init__初始化空对象obj self.__init__(obj,*args,**kwargs) # 在初始化之后,obj.__dict__里就有值了 将属性变成私有的,即隐藏属性 obj.__dict__={‘_%s__%s‘ %(self.__name__,k):v for k,v in obj.__dict__.items()} #3、返回初始化好的对象obj return obj class StanfordTeacher(object,metaclass=Mymeta): school=‘Stanford‘ def __init__(self,name,age): self.name=name self.age=age def say(self): print(‘%s says welcome to the Stanford to learn Python‘ %self.name) t1=StanfordTeacher(‘lili‘,18) print(t1.__dict__) #{‘_StanfordTeacher__name‘: ‘lili‘, ‘_StanfordTeacher__age‘: 18}
控制类的调用即是控制类的对象的产生
class Mymeta(type): #只有及继承了type 类的类才是元类 def __call__(self, *args, **kwargs): print(‘--->‘, self.__name__) # ---> People #1、Mymeta.__call__函数内部会先调用 People 内的__new__ people_obj= self.__new__(self, *args, **kwargs) #得到一个空对象,此处的self是People类 # 查看初始化前的的对象的属性 print(‘people对象初始化前的属性:‘, people_obj.__dict__) # {} #2、Mymeta.__call__函数会调用 People 内的__init__ 初始化对象 self.__init__(people_obj, *args, **kwargs) #初始化空对象 #查看初始化后对象的属性 print(‘people对象初始化后的属性:‘, people_obj.__dict__) # {‘name‘: ‘egon‘, ‘age‘: 18} people_obj.__dict__[‘xxxxx‘] = 11111 # 3、Mymeta.__call__函数内会返回一个初始化好的对象 return people_obj
People = Mymeta() ---> type.__ call __ ==>干了3件事
1、type.__ call __ 函数内会先调用 Mymeta内的 __ new__
2、type.__ call __ 函数内会再调用Mymetan内的 __ init__
3、type.__ call__函数内会返回一个初始化好的对象
lass People(metaclass= Mymeta): def __init__(self, name, age): self.name = name self.age = age def say(self): print(‘%s:%s‘ % (self.name, self.age)) def __new__(cls, *args, **kwargs): #产生真正的people_obj对象 return object.__new__(cls) #调用父类的__new__方法产生空对象
obj = People(‘egon‘, 18) ==> Mymeta.__ call __ ===>干了3件事
1、Mymeta.__ call __ 函数内会先调用People内的 __ new__
2、Mymeta. __ call__ 函数内会调用People内的 __ init__
3、Mymeta.__ call __函数会返回一个初始化好的对象
obj1=People(‘egon‘,18) obj2=People(‘egon‘,18) print(obj1.__dict__) #{‘name‘: ‘egon‘, ‘age‘: 18, ‘xxxxx‘: 11111} print(obj2.__dict__) #{‘name‘: ‘egon‘, ‘age‘: 18, ‘xxxxx‘: 11111}
我们用class自定义的类也全都是对象(包括object类本身也是元类type的 一个实例,可以用type(object)查看)。
属性查找的原则:对象----》类------》父类
注:父类不是元类
属性查找应该分成两层,一层是对象层(基于c3算法的MRO)的查找,另外一个层则是类层(即元类层)的查找
1)类的属性查找,可以找到元类
2)对象的属性查找,找不到元类
class Mymeta(type): #只有及继承了type 类的类才是元类 n=444 def __call__(self, *args, **kwargs): #self=<class ‘__main__.StanfordTeacher‘> obj=self.__new__(self) # StanfordTeacher.__new__ # obj=object.__new__(self) print(self.__new__ is object.__new__) #True self.__init__(obj,*args,**kwargs) return obj class Bar(object): # n=333 # def __new__(cls, *args, **kwargs): # print(‘Bar.__new__‘) # return object.__new__(cls) class Foo(Bar): # n=222 # def __new__(cls, *args, **kwargs): # print(‘Foo.__new__‘) pass class StanfordTeacher(Foo,metaclass=Mymeta): # n=111 def __init__(self,name,age): self.name=name self.age=age obj=StanfordTeacher(‘lili‘,18) print(obj.__dict__) #{‘name‘: ‘lili‘, ‘age‘: 18} # print(obj.n) #报错 print(StanfordTeacher.n) #444 #类的属性查找,可以找到元类 print(StanfordTeacher.n) #自下而上依次注释各个类中的n=xxx,然后重新运行程序,发现n的查找顺序为StanfordTeacher->Foo->Bar->object->Mymeta->type #对象的属性查找,找不到元类 print()
案例二:
class Mymeta(type): #只有及继承了type 类的类才是元类 n=444 def __call__(self, *args, **kwargs): #self=<class ‘__main__.StanfordTeacher‘> obj=self.__new__(self) # StanfordTeacher.__new__ 继承了Bar的__new__方法 # obj=object.__new__(self) print(self.__new__) ##<function Bar.__new__ at 0x107a9f1e0> print(self.__new__ is object.__new__) #False self.__init__(obj,*args,**kwargs) return obj class Bar(object): # n=333 def __new__(cls, *args, **kwargs): print(cls.__new__) #<function Bar.__new__ at 0x107a9f1e0> print(‘Bar.__new__‘) return object.__new__(cls) class Foo(Bar): # n=222 # def __new__(cls, *args, **kwargs): # print(‘Foo.__new__‘) pass class StanfordTeacher(Foo,metaclass=Mymeta): # n=111 def __init__(self,name,age): self.name=name self.age=age obj=StanfordTeacher(‘lili‘,18) print(obj.__dict__) #{‘name‘: ‘lili‘, ‘age‘: 18} # print(obj.n) #报错 ,找不到元类 print(StanfordTeacher.n) #444 可以找到元类 #属性查找顺序:StanfordTeacher->Foo->Bar->object->Mymeta->type
通过自定义元类产生的类的属性查找
分析元类 Mymeta 中__ call __ 里的 self. __ new __的查找
class Mymeta(type): n=444 def __call__(self, *args, **kwargs): #self=<class ‘__main__.StanfordTeacher‘> obj=self.__new__(self) print(self.__new__ is object.__new__) #True class Bar(object): n=333 # def __new__(cls, *args, **kwargs): # print(‘Bar.__new__‘) class Foo(Bar): n=222 # def __new__(cls, *args, **kwargs): # print(‘Foo.__new__‘) class StanfordTeacher(Foo,metaclass=Mymeta): n=111 school=‘Stanford‘ def __init__(self,name,age): self.name=name self.age=age def say(self): print(‘%s says welcome to the Stanford to learn Python‘ %self.name) # def __new__(cls, *args, **kwargs): # print(‘StanfordTeacher.__new__‘) StanfordTeacher(‘lili‘,18) #触发StanfordTeacher的类中的__call__方法的执行,进而执行self.__new__开始查找
总结:
Mymeta下的__ call __ 里的self.__ new __ 在StanfordTeacher、Foo、Bar里都没有找到 __ new __ 的情况下,会去找object里的 __ new __ ,而object下默认就有一个 __ new __ ,所以即便是之前的类均未实现 __ new __ ,也一定会在object中找到一个,根本不会、也根本没必要再去找元类Mymeta->type中查找 __ new__
在元类的__ call __ 中是可以用object.__ new__ (self)去造对象,但是还是推荐在 __ call __ 中使用self. __ new __ (self)去创造空对象,因为这种方式会检索三个类StanfordTeacher->Foo->Bar,而object. __ new __则是直接跨过了他们三个
class Singleton: def __new__: # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr: cls.instance =