練習一:在元類中控制把自定義類的數據屬性都變成大寫spa
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__) """ {'__module__': '__main__', 'COUNTRY': 'China', 'TAG': 'Legend of the Dragon', 'walk': <function Chinese.walk at 0x1040211e0>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None} """
練習二:在元類中控制自定義的類無需init方法code
1.元類幫其完成建立對象,以及初始化操做;對象
2.要求實例化時傳參必須爲關鍵字形式,不然拋出異常TypeError: must use keyword argumentblog
3.key做爲用戶自定義類產生對象的屬性,且全部屬性變成大寫it
class Mymetaclass(type): def __call__(self, *args, **kwargs): if args: raise TypeError('must use keyword argument for key function') obj = object.__new__(self) # 建立對象,self爲類Foo for k,v in kwargs.items(): obj.__dict__[k.upper()] = v return obj class Chinese(metaclass=Mymetaclass): country = 'China' # 須要大寫的數據屬性 tag = 'Legend of the Dragon' def walk(self): print('%s is walking' %self.name) p=Chinese(name='Jack', age=18, sex='male') print(Chinese.__dict__) """ {'__module__': '__main__', 'country': 'China', 'tag': 'Legend of the Dragon', 'walk': <function Chinese.walk at 0x1040211e0>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None} """