Reputation: 135
Say I have a class "NumberStore"
class NumberStore(object):
def __init__(self, num):
self.num = num
def get(self):
return self.num
And later on, for the purpose of serialization, I want to print a definition of the class, either exactly as stated, or equivalently stated. Is there any way in python to access a class's definition as in the idealized example below?
>>> NumberStore.print_class_definition()
"class NumberStore(object):\n def __init__(self, num):\n self.num = num\n \n def get(self):\n return self.num"
Upvotes: 1
Views: 212
Reputation: 46533
Yep, with inspect.getsource
:
from inspect import getsource
class NumberStore(object):
def __init__(self, num):
self.num = num
def get(self):
return self.num
@classmethod
def print_class_definition(cls):
return getsource(cls)
Upvotes: 2
Reputation: 369054
Use inspect.getsource
.
import inspect
source_text = inspect.getsource(NumberStore)
Upvotes: 1