简体   繁体   English

在Python中迭代实例对象的属性

[英]iterate over an instance object's attributes in Python

I have a class 我有一堂课

class MyClass():
    def __init__(self):
        self.a = 7
        self.b = 2
    @property
    def aAndB(self):
        return self.a + self.b

I would like a function that iterates over all properties and returns only class instances having a certain property. 我想要一个遍历所有属性并仅返回具有特定属性的类实例的函数。

My goal is a function like this: 我的目标是这样的功能:

def findInstances(listOfInstances, instanceVariable, instanceValue):
    #return all instances in listOfInstances where instanceVariable==instanceValue

Using instance.__dict__ only gives me a and b , but not aAndB . 使用instance.__dict__仅给我ab ,但给我aAndB I would like to have a dict of all properties/methods with their values to loop over, so I can search for instances where a certain property (or method decorated with @property ) has a certain value. 我想对所有属性/方法及其值进行循环操作,以便我可以搜索某个属性(或用@property装饰的方法)具有某个值的实例。

Currently, calling the function like this 目前,像这样调用函数

findInstances(someListOfInstances, 'aAndB', '23')

makes Python complain that aAndB is not in instance.__dict__. 使Python抱怨aAndB不在instance.__dict__.


Maybe all of you are right and the answers are there, but I still don't get it. 也许所有人都正确,答案就在那里,但我仍然不明白。 All the answers in the mentioned questions get lists, not dictionaries. 提到的问题中的所有答案都是列表,而不是字典。 I want all the properties (including methods with the @property decorator) and their values . 我想要所有属性(包括使用@property装饰器的方法) 及其值 Is there a way to iterate over the values of the keys in dir(myClass) ? 有没有办法遍历dir(myClass)中的键值? The dir command only contains the names of the attributes, not their values. dir命令仅包含属性的名称,而不包含它们的值。

I need something like 我需要类似的东西

for a in dir(myClass):
    print a, myClass.(a)  # get the value for an attribute stored in a variable

To be even more clear: The following achieves exactly what I want but there is probably a better way that I don't know. 更清楚地说:以下内容完全可以实现我想要的功能,但是可能还有我不知道的更好的方法。

for a in dir(myClass):
    print a, eval("myClass.{}".format(a))

There's actually a very simple way to do this, using getattr in place of eval : 实际上,有一种非常简单的方法,使用getattr代替eval

myClass = MyClass()
for a in dir(myClass):
    if(a[:2] != "__"): #don't print double underscore methods
        print a, getattr(myClass, a)

Output: 输出:

a 7
aAndB 9
b 2

This has the very big advantage of not needing to hard code in the name of your instance into the string, as is required using eval("myClass.{}".format(a)) 这具有很大的优点,即不需要像使用eval("myClass.{}".format(a))那样将实例名称硬编码到字符串中eval("myClass.{}".format(a))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM