是否有一种方法可以获取类实例上存在的属性列表?
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"。我希望它能看到脚本各个部分的当前属性。
是否有一种方法可以获取类实例上存在的属性列表?
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"。我希望它能看到脚本各个部分的当前属性。
当前回答
获取对象的属性
class new_class():
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
new_object = new_class(2)
print(dir(new_object)) #total list attributes of new_object
attr_value = new_object.__dict__
print(attr_value) #Dictionary of attribute and value for new_class
for attr in attr_value: #attributes on new_class
print(attr)
输出
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__','__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
{'multi': 4, 'str': '2'}
multi
str
其他回答
使用__dict__或vars是无效的,因为它会遗漏__slots__。 使用__dict__和__slots__不能工作,因为它从基类中遗漏了__slots__。 使用dir不能工作,因为它包含类属性,如方法或属性,以及对象属性。 使用vars相当于使用__dict__。
这是我最好的:
from typing import Dict
def get_attrs( x : object ) -> Dict[str, object]:
mro = type( x ).mro()
attrs = { }
has_dict = False
sentinel = object()
for klass in mro:
for slot in getattr( klass, "__slots__", () ):
v = getattr( x, slot, sentinel )
if v is sentinel:
continue
if slot == "__dict__":
assert not has_dict, "Multiple __dicts__?"
attrs.update( v )
has_dict = True
else:
attrs[slot] = v
if not has_dict:
attrs.update( getattr( x, "__dict__", { } ) )
return attrs
人们经常提到,要列出一个完整的属性列表,应该使用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)
检查模块:
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。
>>> ', '.join(i for i in dir(a) if not i.startswith('__'))
'multi, str'
这当然会打印类定义中的任何方法或属性。你可以通过将i.startwith('__')更改为i.startwith('_')来排除“私有”方法。
Vars (obj)返回对象的属性。