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

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"。我希望它能看到脚本各个部分的当前属性。


当前回答

除了这些答案之外,我还将包括一个函数(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.

其他回答

__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/'
>>>
>>> ', '.join(i for i in dir(a) if not i.startswith('__'))
'multi, str'

这当然会打印类定义中的任何方法或属性。你可以通过将i.startwith('__')更改为i.startwith('_')来排除“私有”方法。

检查模块:

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。

>>> class new_class():
...   def __init__(self, number):
...     self.multi = int(number) * 2
...     self.str = str(number)
... 
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])

您可能还会发现pprint有帮助。

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

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