获取类的属性 [英] Getting attributes of a class

查看:72
本文介绍了获取类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个类的属性,例如:

I want to get the attributes of a class, say:

class MyClass():
  a = "12"
  b = "34"

  def myfunc(self):
    return self.a

使用MyClass.__dict__给我列出了属性和函数,甚至还有__module____doc__之类的函数.除非我显式设置该实例的属性值,否则MyClass().__dict__会给我一个空的字典.

using MyClass.__dict__ gives me a list of attributes and functions, and even functions like __module__ and __doc__. While MyClass().__dict__ gives me an empty dict unless I explicitly set an attribute value of that instance.

我只想要属性,在上面的示例中,这些属性是:ab

I just want the attributes, in the example above those would be: a and b

推荐答案

尝试检查模块. getmembers和各种测试应该会有所帮助.

Try the inspect module. getmembers and the various tests should be helpful.

例如,

class MyClass(object):
    a = '12'
    b = '34'
    def myfunc(self):
        return self.a

>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
 ('__dict__',
  <dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
   '__doc__': None,
   '__module__': '__main__',
   '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
   'a': '34',
   'b': '12',
   'myfunc': <function __main__.myfunc>}>),
 ('__doc__', None),
 ('__module__', '__main__'),
 ('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
 ('a', '34'),
 ('b', '12')]

现在,特殊的方法和属性引起了我的共鸣-可以用多种方法来处理这些方法和属性,最简单的方法就是根据名称进行过滤.

Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.

>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]

......其中更复杂的可以包括特殊的属性名称检查甚至元类;)

...and the more complicated of which can include special attribute name checks or even metaclasses ;)

这篇关于获取类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆