国产探花免费观看_亚洲丰满少妇自慰呻吟_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。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 朔州市| 和顺县| 崇阳县| 巴林右旗| 五峰| 临泽县| 成安县| 吉木萨尔县| 射阳县| 高碑店市| 怀来县| 广州市| 普定县| 蓬安县| 和平区| 齐齐哈尔市| 广河县| 进贤县| 城口县| 云南省| 祁阳县| 射洪县| 龙陵县| 高淳县| 肥乡县| 巩留县| 志丹县| 喜德县| 横峰县| 神池县| 铜梁县| 阿坝| 呼图壁县| 三原县| 鄱阳县| 邵阳县| 高州市| 石棉县| 新野县| 逊克县| 尼勒克县|