首页 文章

在python django中,如何打印出对象的内省?该对象的所有公共方法列表(变量和/或函数)?

提问于
浏览
16

在python django中,如何打印出对象的反射?该对象的所有公共方法列表(变量和/或函数)?

例如 . :

def Factotum(models.Model):
  id_ref = models.IntegerField()

  def calculateSeniorityFactor():
    return (1000 - id_ref) * 1000

我希望能够在Django shell中运行命令行来告诉我Django模型的所有公共方法 . 上面运行的输出将是:

>> introspect Factotoum
--> Variable: id_ref
--> Methods: calculateSeniorityFactor

2 回答

  • 38

    那么,你可以反省的东西很多,而不仅仅是一个 .

    好的开始是:

    >>> help(object)
    >>> dir(object)
    >>> object.__dict__
    

    另请参阅标准库中的inspect模块 .

    这应该使所有基地的99%属于你 .

  • 6

    使用inspect

    import inspect
    def introspect(something):
      methods = inspect.getmembers(something, inspect.ismethod)
      others = inspect.getmembers(something, lambda x: not inspect.ismethod(x))
      print 'Variable:',   # ?! what a WEIRD heading you want -- ah well, w/ever
      for name, _ in others: print name,
      print
      print 'Methods:',
      for name, _ in methods: print name,
      print
    

    有's no way you can invoke this without parentheses in a normal Python shell, you' ll必须使用 introspect(Factotum) ((当然在当前命名空间中导入类 Factotum 属性))和带有空格的 not introspect Factotum . 如果这让你非常烦恼,你可能想看看IPython .

相关问题