练习一:在元类中控制把自定义类的数据属性都变成大写
class MyDef(type): def __new__(cls, class_name, class_attr, class_dic): upper_data = {} for k,v in class_dic.items(): if not callable(v) and not k.startswith('__'): upper_data[k.upper()] = v else: upper_data[k] = v return type.__new__(cls, class_name, class_attr, upper_data) class People(metaclass=MyDef): time = 'now' work = 'weekends' print(People.__dict__)
练习二:在元类中控制自定义的类无需__init__方法
1.元类帮其完成创建对象,以及初始化操作;
2.要求实例化时传参必须为关键字形式,否则抛出异常TypeError: must use keyword argument
3.key作为用户自定义类产生对象的属性,且所有属性变成大写
class MyDef(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 People(metaclass=MyDef): tag = 'China' some = 'None' p1 = People(name = 'panda') print(p1.__dict__)
练习三:在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性
# 在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性 class Mymeta(type): def __init__(self, class_name, class_bases, attr): super(Mymeta, self).__init__(class_name, class_bases, attr) def __call__(self, *args, **kwargs): obj = self.__new__(self) self.__init__(obj, *args, **kwargs ) obj.__dict__ = {'_%s__%s' % (self.__name__, k): v for k, v in obj.__dict__.items()} return obj class P(metaclass=Mymeta): def __init__(self, name, age): self.name = name self.age = age p1 = P('123','567') print(p1._P__name)
练习四:基于元类实现单例模式