国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Python元類編程

2019-11-14 12:43:59
字體:
來源:轉載
供稿:網友

元類讓你來定義某些類是如何被創建的,從根本上說,賦予你如何創建類的控制權。示例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。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临潭县| 桐柏县| 德州市| 南通市| 邵阳市| 赫章县| 汝城县| 庆云县| 陆良县| 临邑县| 吉安县| 十堰市| 海盐县| 贵德县| 永州市| 明水县| 萨嘎县| 年辖:市辖区| 辽阳县| 漯河市| 怀宁县| 临湘市| 仁怀市| 庆元县| 甘德县| 平顶山市| 辰溪县| 吉木乃县| 磐安县| 大丰市| 宜丰县| 无为县| 资兴市| 永康市| 广平县| 沽源县| 岱山县| 绥宁县| 报价| 桂阳县| 弥渡县|