是否有一种方法可以获取类实例上存在的属性列表?

class new_class():
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

a = new_class(2)
print(', '.join(a.SOMETHING))

期望的结果是输出"multi, str"。我希望它能看到脚本各个部分的当前属性。


当前回答

__attrs__给出了一个实例的属性列表。

>>> import requests
>>> r=requests.get('http://www.google.com')
>>> r.__attrs__
['_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request']
>>> r.url
'http://www.google.com/'
>>>

其他回答

检查模块:

inspect模块提供了几个有用的函数来帮助获取 有关活动对象的信息,如模块、类、方法、 函数、回溯、帧对象和代码对象。


使用getmembers()可以看到类的所有属性及其值。要排除私有或受保护的属性,请使用. startwith('_')。要排除方法或函数,请使用inspect.ismethod()或inspect.isfunction()。

import inspect


class NewClass(object):
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

    def func_1(self):
        pass


inst = NewClass(2)

for i in inspect.getmembers(inst):
    # Ignores anything starting with underscore 
    # (that is, private and protected attributes)
    if not i[0].startswith('_'):
        # Ignores methods
        if not inspect.ismethod(i[1]):
            print(i)

注意,ismethod()用于i的第二个元素,因为第一个元素只是一个字符串(它的名字)。

跑题:类名使用CamelCase。

你可以使用dir(your_object)来获取属性,使用getattr(your_object, your_object_attr)来获取值

用法:

for att in dir(your_object):
    print (att, getattr(your_object,att))

如果你的对象没有__dict__,这特别有用。如果不是这样,你也可以尝试var(your_object)

dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__

然后可以用type()测试类型是什么,或者用callable()测试是否为方法。

人们经常提到,要列出一个完整的属性列表,应该使用dir()。但是请注意,与普遍观点相反,dir()并没有显示所有属性。例如,你可能会注意到__name__可能在类的dir()列表中缺失,即使你可以从类本身访问它。从dir()的文档(Python 2, Python 3):

因为提供dir()主要是为了方便在 交互式提示符,它试图提供一组有趣的名称 它不仅仅是试图提供一个严格或一致定义的集合 的名称,其详细行为可能在不同版本之间更改。为 属性时,元类属性不在结果列表中 参数是一个类。

像下面这样的函数往往更完整,尽管不能保证完整性,因为dir()返回的列表可能受到许多因素的影响,包括实现__dir__()方法,或在类或其父类之一上自定义__getattr__()或__getattribute__()。详情请参阅所提供的链接。

def dirmore(instance):
    visible = dir(instance)
    visible += [a for a in set(dir(type)).difference(visible)
                if hasattr(instance, a)]
    return sorted(visible)

除了这些答案之外,我还将包括一个函数(python 3),用于输出任何值的几乎整个结构。它使用dir来建立属性名的完整列表,然后对每个名称使用getattr。它会显示值的每个成员的类型,如果可能的话还会显示整个成员:

import json

def get_info(obj):

  type_name = type(obj).__name__
  print('Value is of type {}!'.format(type_name))
  prop_names = dir(obj)

  for prop_name in prop_names:
    prop_val = getattr(obj, prop_name)
    prop_val_type_name = type(prop_val).__name__
    print('{} has property "{}" of type "{}"'.format(type_name, prop_name, prop_val_type_name))

    try:
      val_as_str = json.dumps([ prop_val ], indent=2)[1:-1]
      print('  Here\'s the {} value: {}'.format(prop_name, val_as_str))
    except:
      pass

现在,以下任何一项都应该让你有所了解:

get_info(None)
get_info('hello')

import numpy
get_info(numpy)
# ... etc.