1
def classDecorator(aClass):
    def variables(self):
        for variable in self.__dict__:
            if isinstance(variable, int):
                yield variable
    setattr(aClass, 'variables', variables)
    return aClass

@classDecorator
class myClass:
    pass

if __name__ == '__main__':
    x = myClass()
    x.a = 2
    print(str(x.variables()))

This decorator should add a method to the class that returns an iterator of the instance variables of type int of the instance it is invoked by, but if I run the program it prints this:

<generator object classDecorator.<locals>.variables at 0x011385D8>

Why?

  • 3
    That's the iterator. You have to iterate over it to get the actual attribute names. Try `print(list(x.elencaVariabili()))`. – chepner Sep 07 '20 at 20:10
  • `print(str(x.elencaVariabili().__next__()))` would print the first int, to print all the ints you need to iterate over the function, e.g. `for some_int in x.elencaVariabili()` – rotem tal Sep 07 '20 at 20:14
  • Does this answer your question? [Understanding generators in Python](https://stackoverflow.com/questions/1756096/understanding-generators-in-python) – flakes Sep 07 '20 at 20:14
  • @chepner it prints an empty list [] – user14223968 Sep 07 '20 at 20:19
  • @rotemtal it gives me StopIteration error – user14223968 Sep 07 '20 at 20:22
  • that's likely since variables cannot be ints, iterating over a dictionary is iterating over it's keys, since in the dictionary representation of a class the variables are the keys, no key would be an instance of int (e.g. you wont have `self.1 = x`). if you want variables whose assignment is an int you should iterate over values, or just use the line `if isinstance(self.dict[variable],int)` – rotem tal Sep 07 '20 at 20:27
  • Indeed: if you want a list of the values, `for variable in self.__dict__.values()`:. If you want a list of the names, `if isinstance(self.__dict__[variable], int):` – chepner Sep 07 '20 at 20:29

1 Answers1

1

The loop for variable in self.__dict__ will give you the names of the variables (as a sequence of strings). To get the values, can use this:

for var, value in self.__dict__.items():
    if isinstance(value, int):
        yield var

In addition, use list() to collect the values yielded by the iterator, as shown in the comments:

print(list(x.variables()))
alexis
  • 43,587
  • 14
  • 86
  • 141