2017-10-17 7 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'} 

は、私は、オブジェクトの本のステートメントを取得するためのさらなるステップに行きます。 出力Iの意図は、だから私はinspectライブオブジェクトの情報を取得するために

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

エラーがPythonのドキュメントは、元のテキストを返します」を指定し、しかし

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

を報告インポート{'title': 'Think Python', 'author': 'Allen','get_entry':statements}

ですオブジェクトのコード。引数は、モジュール、クラス、メソッド、関数、トレースバック、フレーム、またはコードオブジェクトです。ソースコードは単一の文字列として返されます。 OSErrorは、ソースコードを取得できない場合に発生します。 29.12. inspect — Inspect live objects — Python 3.6.3 documentation ここで何が間違っていますか?

+1

クラス自体に 'getsource'を渡す必要があり、インスタンスではありません。 'inspect.getsource(Book)'が動作します。 – nutmeg64

答えて

1

の機能は、クラスのインスタンスではなく、クラスとともに動作します。だから、あなたは次のようにそれを渡す必要があるだろう:

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

いうより:

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

クラスの店舗コードの青写真を、インスタンスには、独自の値を持つその青写真の唯一のバージョンです。したがって、クラスを渡す必要があります。

関連する問題