从Python对象中获取列表

时间:2015-11-18 19:19:40

标签: python list object

我有一个叫做语言的对象:

class Language():
    niceGreetings = ["Hello", "Hi"]
    referToSelf = ["Me", "I"]
    referToCollective = ["We", "Us"]
    referToObject = ["The","It"]
    travelPastTense = ["Went"]
    directionNonSpecific = ["To", "From"]

我想得到一个功能,基本上:

<< listLists(Language)
>> ["niceGreetings", "referToSelf", "referToCollective", etc.]

它几乎必须在Python 2和3之间兼容,但我对此有点灵活

2 个答案:

答案 0 :(得分:1)

dir(Language)开始。

输出:

['__doc__',
 '__module__',
 'directionNonSpecific',
 'niceGreetings',
 'referToCollective',
 'referToObject',
 'referToSelf',
 'travelPastTense']

您可以按如下方式过滤结果:

[field for field in dir(Language) if not field.startswith("__")]

输出:

['directionNonSpecific',
 'niceGreetings',
 'referToCollective',
 'referToObject',
 'referToSelf',
 'travelPastTense']

答案 1 :(得分:0)

您可以获取对象的所有属性列表并过滤列表:

[v for v in Language.__dict__.items() if isinstance(v, list)]