1、在元类中控制把自定义类的数据属性都变成大写
class Metaclass(type):
def __new__(cls, class_name,bases_class_name,attribute_dict):
update_dict={}
for k,v in attribute_dict.items():
if not callable(v) and not k.startswith('__'):
update_dict[k.upper()]=v
else:
update_dict[k]=v
return type.__new__(cls,class_name,bases_class_name,update_dict)
class Teacher(metaclass=Metaclass):
hobby="Say you're the worst student I've ever brought"
dream='Engineer of human soul'
def say_job(self):
print(f'my job is {self.name}')
print(Teacher.__dict__)
2、在元类中控制自定义的类无需__init__方法
# 2.要求实例化时传参必须为关键字形式,否则抛出异常TypeError: must use keyword argument
#
# 3.key作为用户自定义类产生对象的属性,且所有属性变成大写
# 3、在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性
class Metaclass(type):
def __call__(self, *args, **kwargs):
if args:
raise TypeError('必须传入关键字参数')
obj=object.__new__(self)
for k,v in kwargs.items():
obj.__dict__[k.upper()]=v
return obj
class Teacher(metaclass=Metaclass):
hobby="Say you're the worst student I've ever brought"
dream='Engineer of human soul'
def say_job(self):
pass
p=Teacher(name='tom',age=18,sex='male')
print(p.__dict__)
3、在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性
class Metaclass(type):
def __init__(self, class_name, bases_class_name, attribute_dict):
super().__init__(class_name, bases_class_name, attribute_dict)
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 Foo(object, metaclass=Metaclass):
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
obj = Foo('tom', 18, 'male')
print(obj.__dict__)