元類讓你來定義某些類是如何被創建的,從根本上說,賦予你如何創建類的控制權。示例1,它在用元類創建一個類時,顯示時間標簽。
#!/usr/bin/env pythonfrom time import ctimeclass MetaC(type): def __init__(cls, name, bases, attrd): super(MetaC, cls).__init__(name, bases, attrd) 輸出:*** Created class 'Foo' at: Wed Feb 9 11:50:37 2011*** Instantiated class 'Foo' at: Wed Feb 9 11:50:37 2011示例2,將創建一個元類,要求程序員在他們寫的類中提供一個str()方法的實現。
#!/usr/bin/env pythonfrom warnings import warnclass ReqStrSugRepr(type): def __init__(cls, name, bases, attrd): super(ReqStrSugRepr, cls).__init__(name, bases, attrd) if '__str__' not in attrd: raise TypeError("Class requires overriding of __str__()") if '__repr__' not in attrd: warn('Class suggests overriding of __repr__()/n', stacklevel=3)class Foo(object): __metaclass__ = ReqStrSugRepr def __str__(self): return 'Instance of class:', self.__class__.__name__ def __repr__(self): return self.__class__.__name__class Bar(object): __metaclass__ = ReqStrSugRepr def __str__(self): return 'Instance of class:', self.__class__.__name__class FooBar(object): __metaclass__ = ReqStrSugRepr輸出:
sys:1: UserWarning: Class suggests overriding of __repr__()Traceback (most recent call last): File "/home/zhangjun/workspace/try/src/try.py", line 29, in <module> class FooBar(object): File "/home/zhangjun/workspace/try/src/try.py", line 9, in __init__ raise TypeError("Class requires overriding of __str__()")TypeError: Class requires overriding of __str__()簡單說明一下,定義元類ReqStrSugRepr,如果沒有__str__()
方法的實現,則會拋出一個異常,而如果沒有__repr__()
方法的實現,則會打印出一個UserWarning。Foo 定義成功的;定義Bar 時,提示警告__repr__()
未實現;FooBar 的創建沒有通過安全檢查,以致程序最后沒有打印出關于FooBar 的Traceback。
新聞熱點
疑難解答