如何在python中返回类的定义?

时间:2014-06-07 08:04:10

标签: python class oop metaprogramming

说我有一个班级“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"

2 个答案:

答案 0 :(得分:2)

是的,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)

答案 1 :(得分:1)

使用inspect.getsource

import inspect
source_text = inspect.getsource(NumberStore)