[英]iterate over an instance object's attributes in Python
我有一堂课
class MyClass():
def __init__(self):
self.a = 7
self.b = 2
@property
def aAndB(self):
return self.a + self.b
我想要一个遍历所有属性并仅返回具有特定属性的类实例的函数。
我的目标是这样的功能:
def findInstances(listOfInstances, instanceVariable, instanceValue):
#return all instances in listOfInstances where instanceVariable==instanceValue
使用instance.__dict__
仅给我a
和b
,但不给我aAndB
。 我想对所有属性/方法及其值进行循环操作,以便我可以搜索某个属性(或用@property
装饰的方法)具有某个值的实例。
目前,像这样调用函数
findInstances(someListOfInstances, 'aAndB', '23')
使Python抱怨aAndB
不在instance.__dict__.
也许所有人都正确,答案就在那里,但我仍然不明白。 提到的问题中的所有答案都是列表,而不是字典。 我想要所有属性(包括使用@property
装饰器的方法) 及其值 。 有没有办法遍历dir(myClass)
中的键值? dir
命令仅包含属性的名称,而不包含它们的值。
我需要类似的东西
for a in dir(myClass):
print a, myClass.(a) # get the value for an attribute stored in a variable
更清楚地说:以下内容完全可以实现我想要的功能,但是可能还有我不知道的更好的方法。
for a in dir(myClass):
print a, eval("myClass.{}".format(a))
实际上,有一种非常简单的方法,使用getattr
代替eval
:
myClass = MyClass()
for a in dir(myClass):
if(a[:2] != "__"): #don't print double underscore methods
print a, getattr(myClass, a)
输出:
a 7
aAndB 9
b 2
这具有很大的优点,即不需要像使用eval("myClass.{}".format(a))
那样将实例名称硬编码到字符串中eval("myClass.{}".format(a))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.