python3 元類編程的一個例子

來源:互聯網
上載者:User

標籤:沒有   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 元類編程的一個例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.