练习一:在元类中控制把自定义类的数据属性都变成大写
class Mymetaclass(type): def __new__(cls,name,bases,attrs): update_attrs={} for k,v in attrs.items(): if not callable(v) and not k.startswith('__'): update_attrs[k.upper()]=v else: update_attrs[k]=v return type.__new__(cls,name,bases,update_attrs) class Chinese(metaclass=Mymetaclass): country='China' tag='Legend of the Dragon' def walk(self): print('%s is walking' %self.name) print(Chinese.__dict__)
练习二:在元类中控制自定义的类无需__init__方法
1.元类帮其完成创建对象,以及初始化操作;
2.要求实例化时传参必须为关键字形式,否则抛出异常TypeError: must use keyword argument
3.key作为用户自定义类产生对象的属性,且所有属性变成大写
class Mymeta(type): def __call__(self, *args, **kwargs): if args: raise TypeError ('must use keyword argument') obj = object.__new__(self) for k ,v in kwargs.items(): obj.__dict__[k.upper()] = v return obj class a(metaclass=Mymeta): tag= "legond of Dragon" def walk(self): print("%s is walking "%self.tag) p = a(name='egon',age=18,sex='male') print(p.__dict__)
练习三:在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性
class mt(type): def __init__(self,classname,bases,class_dic): print(self)#<class '__main__.Foo'> print(classname)#Foo print(bases)#(<class 'object'>,) print(class_dic)#{'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x00000000024AAC80>} super().__init__(classname,bases,class_dic) def __call__(self, *args, **kwargs): print(self)#<class '__main__.Foo'> print(args)#('egon', 18, 'man') print(kwargs)#{} obj = object.__new__(self) self.__init__(self,*args,**kwargs) for k,v in self.__dict__.items(): obj.__dict__["_%s__%s"%(self.__name__,k)] = v return obj class Foo(object,metaclass=mt): def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex a = Foo("egon",18,"man") print(a.__dict__) """ '_Foo____module__': '__main__', '_Foo____init__': <function Foo.__init__ at 0x000000000251AD08>, '_Foo____dict__': <attribute '__dict__' of 'Foo' objects>, '_Foo____weakref__': <attribute '__weakref__' of 'Foo' objects>, '_Foo____doc__': None, '_Foo__name': 'egon', '_Foo__age': 18, '_Foo__sex': 'man'} """
练习四:基于元类实现单例模式
""" 练习四:基于元类实现单例模式 """ class mt(type): instance = None def __call__(self, *args, **kwargs): if not mt.instance: mt.instance = self.__new__(self)#生成一个空对象 mt.instance.__init__(*args,**kwargs)#初始化对象 return mt.instance #返回对象 class Foo(object,metaclass=mt): def __init__(self,name,age): self.name = name self.age = age def walk(self): print("%s is walking"%self.name) p1 = Foo("egon",18) p2 = Foo("egon",18) print(p1) print(p2)