標籤:沒有 version raise init name not 工程師 doc sel
【引子】
雖然我們可以通過“class”語句來定義“類”,但是要想更加細粒度的控制“類”的建立,要使用元類編程才能實現。
比如說我們要實現這樣的一個約束、所有項目中用到的類都應該要為它定義的方法提供文檔字元字串。有兩條可行
的路徑 1):依賴工程師的自覺、自律 讓他們在定義每一個方法的時候都為方法增加文檔字串, 2):通過元類來做一些
控制,如果工程師沒有為方法提供文檔字元,那麼就直接報錯,直到工程師為方法提供字串為止。
【實現1】
依賴工程師的自覺、自律為方法增加文檔字串
class Person(object): name = None def __init__(self,name): self.name=name def say_hello(self): """ print hello My name is xxx ... """ print("hello My name is {self.name}".format(self=self))
我們如何能保證每一個方法都增加了文檔字串呢?我一方面要依靠“自覺”另一方面要依靠“紀律性”,最好要有專門的人來做代碼
審核。
【實現2】
通過元類來實現這個約束
第一步:定義一個元類來審核class
class DocMeta(type): """ 檢查方法是否有提供文檔字串 """ def __init__(self,name,base,attrs):for key,value in attrs.items(): if key.startswith(‘__‘): #跳過魔術方法 continue if not hasattr(value,"__call__"): #跳過欄位 continue #如果能進入到這裡、那麼一定是方法了、於是檢查方法有沒有文檔字串. if not getattr(value,"__doc__"): #沒有文檔字串的情況下就報錯 raise TypeError("{0} must have a docstring".format(key)) super().__init__(name,base,attrs)
第二步:定義一個通用的基類、以後所有要實現這一約束的類都繼承自它
class Documented(metaclass=DocMeta): pass
注意這個項的元類是我們剛才定義的“DocMeta”類
第三步:讓項目中的類繼承自這個基類
class Person(Documented): name = None def __init__(self,name): self.name=name def say_hello(self): """ print hello My name is xxx ... """ print("hello My name is {self.name}".format(self=self))
第四步:和使用普通的類一樣使用Person類
if __name__=="__main__": p = Person("welson") p.say_hello() #hello My name is welson
【總結】
以上代碼由於在say_hello 方法中提供了文檔字串、如果沒有提供的話、在建立Person類的時候就會報錯了
Traceback (most recent call last): File "main.py", line 31, in <module> class Person(Documented): File "main.py", line 24, in __init__ raise TypeError("{0} must have a docstring".format(key))TypeError: say_hello must have a docstring
全部代碼如下:
"""Python元類編程的一個例子"""__version__ = ‘0.1‘__author__ = ‘蔣樂哥哥‘class DocMeta(type): """ 檢查方法是否有提供文檔字串 """ def __init__(self,name,base,attrs): for key,value in attrs.items(): if key.startswith(‘__‘): #路過魔術方法 continue if not hasattr(value,"__call__"): #跳過欄位 continue #如果能進入到這裡、那麼一定是方法了、於是檢查方法有沒有文檔字串. if not getattr(value,"__doc__"): #沒有文檔字串的情況下就報錯 raise TypeError("{0} must have a docstring".format(key)) super().__init__(name,base,attrs)class Documented(metaclass=DocMeta): passclass Person(Documented): name = None def __init__(self,name): self.name=name def say_hello(self): """ print hello My name is xxx ... """ print("hello My name is {self.name}".format(self=self))# 在不為方法提供文檔字串的情況下會直接報錯#class Person(Documented):# name = None# def __init__(self,name):# self.name=name## def say_hello(self):# print("hello My name is {self.name}".format(self=self))if __name__=="__main__": p = Person("welson") p.say_hello()
----------------------------------------
python3 元類編程的一個例子