1. 程式人生 > >面向對象進階6:元類

面向對象進階6:元類

ise and 否則 tag weak wal 方法 pan strong

六 練習題

練習一:在元類中控制把自定義類的數據屬性都變成大寫

技術分享圖片
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 0x0000000001E7B950>, ‘__dict__‘: <attribute ‘__dict__‘ of ‘Chinese‘ objects>, ‘__weakref__‘: <attribute ‘__weakref__‘ of ‘Chinese‘ objects>, ‘__doc__‘: None}
‘‘‘
View Code

練習二:在元類中控制自定義的類無需__init__方法

  1.元類幫其完成創建對象,以及初始化操作;

  2.要求實例化時傳參必須為關鍵字形式,否則拋出異常TypeError: must use keyword argument

  3.key作為用戶自定義類產生對象的屬性,且所有屬性變成大寫

技術分享圖片
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) 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=egon,age=18,sex=male) print(p.__dict__)
View Code

面向對象進階6:元類