1

I would like to write a function to append an attribute of a Python object, the attribute is a list.

Here is my code, which sets the attribute to a given value. Is there a simpler/cleaner way to this..

class Obj(object):
    def __init__(self):
        self.a = 2
        self.b = []
        self.c = []

    def append_att(self, att):
        at = getattr(self, att)
        at.append(self.a)
        setattr(self,att, at)
obj = Obj()
obj.append_att('b')
obj.append_att('b')
print obj.b
4
  • 4
    This looks like an XY problem, what are you trying to actually achieve? Commented Dec 5, 2017 at 15:23
  • 3
    FWIW, you could simply do: getattr(self, att).append(self.a) Commented Dec 5, 2017 at 15:26
  • 1
    Why are you doing setattr(self,att, at)? Commented Dec 5, 2017 at 15:29
  • 1
    Explicit is better than implicit! You would normally do getattr(obj, 'b').append(obj.a) without defining any methods. self.b holds reference to the list instance and you don't have to reassign it. Modification to the list is transparently seen by self.b. Commented Dec 5, 2017 at 15:33

1 Answer 1

2

You can use self.__dict__ to append to the list with the same string variable name as the value to be added to the list:

class Obj(object):
   def __init__(self):
      self.a = 2
      self.b = []
      self.c = []
   def append_att(self, att):
      self.__dict__[att].append(self.a)

o = Obj()
o.append_att('b')
o.append_att('b')
o.append_att('c') 
print(o.b)
print(o.c)

Output:

[2, 2]
[2]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.