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

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

Python元類編程

2019-11-14 11:48:57
字體:
來源:轉載
供稿:網友

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 满城县| 北碚区| SHOW| 滕州市| 新建县| 嘉兴市| 新和县| 分宜县| 澳门| 噶尔县| 凤山县| 孟村| 黄骅市| 临海市| 平阳县| 当阳市| 北辰区| 汕头市| 航空| 梅河口市| 金秀| 漳州市| 屏南县| 紫金县| 封丘县| 吉木乃县| 金门县| 长治县| 津南区| 金昌市| 青岛市| 南陵县| 弥渡县| 泸水县| 浠水县| 鹤庆县| 阳春市| 湛江市| 利津县| 舒兰市| 临邑县|