簡體   English   中英

如何在不實例化課程的情況下獲取班級成員的完整列表?

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

美好的一天!

我正在寫一個小工具,為我的數據感知應用程序構建一個GUI。

基本思想是獲得一個包含模型描述( sqla/elixir實體)作為輸入的模塊,並向用戶顯示可用類(從Entity()繼承)及其字段(從Field()繼承)的列表。從這個模塊。

pyclbr模塊非常適合獲取類及其方法,但無法讀取其他類成員。 我知道__dict__inspect模塊,但是問題是它們需要實例化一個有問題的類,在這種情況下這是錯誤的。 那么,還有另一種方法嗎?

我真的不想將模塊解析為文本。 :)

我不確定我是否知道您的意思:

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

print dir(a)

版畫

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

您可以使用

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

如果您不想看到特殊的方法。

您無需實例化該類即可查看其成員。 您不會看到在方法內部添加的屬性,但是類定義或元類的__new__方法中定義的所有內容都將存在。

請參閱我對inspect.getmembers()與__dict __。items()與dir()的回答,以獲取有關這些不同函數究竟返回什么的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM