-1

I am looking for the possibility to add a variable amount of attributes to a class in python using a list.

class X():

    def __init__(self,mylist):
        for element in list:
        self.element = ''

So if I have

tabs = ['food','name','map']

I will get a class with attributes as follows (pseudocode)

myclass = X(['food','name','map'])

print(X.food)
''

I will be able later on to modify X.food from other class.

LATE EDIT: The question: How to access object attribute given string corresponding to name of that attribute is similar but does not use a list to provide names or arguments to the class. Moreover in that particular question setattr is not used in any of the answers. Hence the answers of this question are the ones to follow.

JFerro
  • 3,203
  • 7
  • 35
  • 88

2 Answers2

1

You can use setattr.

class X:
    def __init__(self, attrs):
        for attr in attrs:
            setattr(self, attr, "")
gold_cy
  • 13,648
  • 3
  • 23
  • 45
0

Use setattr:

class X():
    def __init__(self,mylist):
        for element in mylist:
            setattr(self, element, '')

This adds the attributes to the class instance myclass, if you want to add to the class target X instead of self:

            setattr(X, element, '')
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
  • this answer is an exact duplicate of the one I posted a [minute earlier](https://stackoverflow.com/questions/70369668/python-add-a-variable-numbers-of-attributes-to-a-python-class?answertab=oldest#tab-top) – gold_cy Dec 15 '21 at 20:10
  • You posted `10s` earlier, while i was editing mine. – Pedro Maia Dec 15 '21 at 20:12
  • 1
    @gold_cy guys well no, not exact. And it isn't hard to believe that two people would write the exact same answer. In **any case** this is such an obvious duplicate that it should have been flagged as one instead of answering it – juanpa.arrivillaga Dec 15 '21 at 20:12