简体   繁体   中英

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 . 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.

Currently, calling the function like this

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

makes Python complain that aAndB is not in 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 . Is there a way to iterate over the values of the keys in dir(myClass) ? The dir command only contains the names of the attributes, not their values.

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 :

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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