![](/img/trans.png)
[英]How can I get the type of a class without instantiating it in Python?
[英]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.