0

I want to iterate on self attributes from self function in Python3, but I have not found any similar. I found how to do it outside the class here.

My question is, is it possible?

class Foo:

    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

    def method1(self):
        #Return sum of the values of the self attributes
        pass
Sergio Rodríguez Calvo
  • 1,183
  • 2
  • 16
  • 32

2 Answers2

4

You can access all attributes via the __dict__ member:

class Foo:

    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

    def method1(self):
        return sum(self.__dict__.values())

You can also use vars (thanks to Azat Ibrakov and S.M.Styvane for pointing this out):

    def method1(self):
        return sum(vars(self).values())

Here is a nice discussion on __dict__ vs. vars().

themiurge
  • 1,619
  • 17
  • 21
3

I am not a big fan of using __dict__ for simple things. You should use vars to return a dict of your instance attributes

>>> class Foo(object):
...     def __init__(self, attr1, attr2):
...         self.attr1 = attr1
...         self.attr2 = attr2
...     def method1(self):
...         return sum(vars(self).values())
... 
>>> Foo(2, 4).method1()
6
styvane
  • 59,869
  • 19
  • 150
  • 156