说我有一个班级“NumberStore”
class NumberStore(object):
def __init__(self, num):
self.num = num
def get(self):
return self.num
后来,为了序列化,我想打印一个类的定义,或者完全按照规定,或者等效地说明。有没有办法在python中访问类的定义,如下面的理想化示例?
>>> 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"
答案 0 :(得分:2)
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)
答案 1 :(得分:1)
import inspect
source_text = inspect.getsource(NumberStore)