如何在python中返回类的定义? [英] How do I return the definition of a class in python?

查看:83
本文介绍了如何在python中返回类的定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个"NumberStore"类

Say I have a class "NumberStore"

class NumberStore(object):
    def __init__(self, num):
        self.num = num

    def get(self):
        return self.num

然后,出于序列化的目的,我想打印类的定义,该定义完全相同或相同. python中有什么方法可以访问类的定义,如下面的理想示例所示?

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"

推荐答案

是的,使用

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)

这篇关于如何在python中返回类的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆