我需要获得一个干净的列表,列出我在课堂上定义的所有属性的名称。让我们说我有下一堂课:
class MyClass(object):
attr1 = None
attr2 = 2
attr3 = "Hello world"
我想知道是否有某些东西允许我这样做:
>>> some_method(MyClass) # <- check class
['attr1', 'attr2', 'attr3']
>>> my_class = MyClass()
>>> some_method(my_class) # <- check instance of MyClass
['attr1', 'attr2', 'attr3']
我不能依赖内置方法dir
,因为它还会返回__class__
,__getattr__
等属性以及类所具有的任何方法。我的意思是,我需要 ONLY 在类中定义的属性,而不是内置的属性,也不是方法。
这甚至可能吗?或者有什么方法可以知道哪些属性是内置的,哪些属性是由我定义的,这样我就可以遍历列表dir
返回并进行一些filter
?
提前感谢您的帮助!!
答案 0 :(得分:5)
这是一个起点:
>>> [x for x in dir(a) if not x in dir(super(type(a)))]
['__dict__', '__module__', '__weakref__', 'attr1', 'attr2', 'attr3']
返回对象dir
中不是来自其父类“dir
的所有内容。
它做得好的一件事就是过滤掉类中定义的方法,但不要触摸恰好是函数的实例属性。
答案 1 :(得分:2)
函数是也是属性,没有什么能阻止你以后为类或实例分配其他函数。所以你问你是否可以列出不函数的所有属性,而不是'特殊'。
如果要列出在类或实例上直接定义的任何内容,请查看.__dict__
映射。你仍然需要过滤:
import types
def objectAttributes(obj):
for key, val in obj.__dict__.iteritems():
if not isinstance(val, (types.FunctionType, types.MethodType)):
yield key
这将生成所有非函数或方法的属性名称,这些属性名称既适用于类,也适用于手动分配方法的实例。
要将列表作为输出,请致电list(objectAttributes(MyClass))
或list(objectAttributes(myinstance))
。
此方法不遍历基类,如果您在班级上使用__slots__
,则会失败。
答案 2 :(得分:2)
您可以使用inspect模块执行此操作。
以下是一个例子:
>>> import inspect
>>> filter(lambda x: not (x.startswith('__') and x.endswith('__')), [a for (a, b) in inspect.getmembers(MyClass, lambda x : (not inspect.ismethod(x) and not inspect.isbuiltin(x)) )])
['attr1', 'attr2', 'attr3']
基本思想是运行inspect.getmembers
以获取某个对象的所有成员。这既支持对象也支持类。使用作为inspect.getmembers
的可选参数提供的谓词lambda表达式过滤方法和内置函数。然后,list comprehension用于获取每个成员的名称,最后使用Python过滤器函数过滤掉__dict__
等。
对__dict__
等的过滤不是很“科学”,但我认为它应该适用于大多数情况:)
答案 3 :(得分:0)
t = MyClass()
result = []
for k,v in t.__dict__.items(): #all members of MyClass
if not hasattr(v, '__call__'):#if it's not a callable
result.append(k)