2017-10-17 71 views
1

假設一類如何檢索對象的源代碼?

class Book(object): 
    def __init__(self, title, author): 
     self.title = title 
     self.author = author 
    def get_entry(self): 
     return self.__dict__ 

創建一個實例:

>>> book = Book('Think Python', 'Allen') 
>>> vars(book) 
{'title': 'Think Python', 'author': 'Allen'} 

我去進一步的步驟來檢索對象本書的說法。 輸出我的意圖是{'title': 'Think Python', 'author': 'Allen','get_entry':statements}

於是我進口inspect獲得活動對象的信息

>>> import inspect 
>>> inspect.getsource(book) 

錯誤報告

TypeError: <__main__.Book object at 0x10f3a0908> is not a module, class, method, function, traceback, frame, or code object 

然而,蟒蛇文檔指定「返回源文本代碼爲一個對象。參數可以是模塊,類,方法,函數,追溯,框架或代碼對象。源代碼作爲單個字符串返回。如果無法檢索源代碼,則會引發OSError。' 29.12. inspect — Inspect live objects — Python 3.6.3 documentation 這裏有什麼問題?

+1

您需要傳遞'getsource'類本身而不是實例。 'inspect.getsource(Book)'會起作用。 – nutmeg64

回答

1

getsource函數適用於類而不是類的實例。所以,你必須按如下方式傳遞:

inspect.getsource(Book) # Book is the class, defined by 'class Book:' 

,而不是:代碼藍圖

inspect.getsource(book) # where book is an Instance of the Book class. 

類賣場,例如只與自己的價值觀是藍圖的一個版本。因此,你需要通過課程。