How do I return the definition of a class in pytho

2019-07-27 22:44发布

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"

2条回答
神经病院院长
2楼-- · 2019-07-27 23:17

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)
查看更多
在下西门庆
3楼-- · 2019-07-27 23:26

Use inspect.getsource.

import inspect
source_text = inspect.getsource(NumberStore)
查看更多
登录 后发表回答