简体   繁体   English

如何在不实例化课程的情况下获取班级成员的完整列表?

[英]How can I get a full list of class members without instantiating a class?

Good day! 美好的一天!

I'm writing a little tool that builds a GUI for my data-aware app. 我正在写一个小工具,为我的数据感知应用程序构建一个GUI。

The basic idea is to get a module containing a model description ( sqla/elixir entities) as an input, and to present the user with a list of available classes (inherited from Entity() ) and their fields (inherited from Field() ) from this module. 基本思想是获得一个包含模型描述( sqla/elixir实体)作为输入的模块,并向用户显示可用类(从Entity()继承)及其字段(从Field()继承)的列表。从这个模块。

The pyclbr module is fine for getting classes and their methods, but it can't read other class-members. pyclbr模块非常适合获取类及其方法,但无法读取其他类成员。 I know about __dict__ and inspect module, but the problem is they require instantiation of a class in question, and that is kind of wrong in this context. 我知道__dict__inspect模块,但是问题是它们需要实例化一个有问题的类,在这种情况下这是错误的。 So, is there another way ? 那么,还有另一种方法吗?

I really don't want to parse modules as text. 我真的不想将模块解析为文本。 :) :)

I'm not sure I know what you mean: 我不确定我是否知道您的意思:

class a(object):
    b = 'a'
    c = 'd'

print dir(a)

prints 版画

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'b', 'c']

You can use 您可以使用

print [i for i in dir(a) if not i.endswith('__')]

if you don't want to see the special methods. 如果您不想看到特殊的方法。

You don't need to instantiate the class to see it's members. 您无需实例化该类即可查看其成员。 You won't see attributes added inside methods, but everything defined in the class definition or a metaclass' __new__ method will be there. 您不会看到在方法内部添加的属性,但是类定义或元类的__new__方法中定义的所有内容都将存在。

See my answer to inspect.getmembers() vs __dict__.items() vs dir() for more info on what exactly these different functions return. 请参阅我对inspect.getmembers()与__dict __。items()与dir()的回答,以获取有关这些不同函数究竟返回什么的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM