2

how can i create multiple attribute by list, for example:

my code:

class test():
    def __init__(self, name):
       pass...
    def test2(self, lista):

but in this method i create one object (the final element of my list. How can i create multiple self.ris to generate multiple object?

2 Answers 2

1

Use setattr to set the attribute's name to a variable:

class pkg():
    def __init__(self, name):
            self.name = name
            lista_ = self.dai_lista(lista)
            print lista_
            for i in lista_:
                    i = i.rstrip()
                    setattr(self, 'ris'+i, riso(i))
    def dai_lista(self, lista):
            print "sono in dai lista"
            return lista

class riso():
        def __init__(self, nome):
                self.nome = nome
        def print_nome(self):
                print self.nome

lista = ['a', 'b', 'c' ]
pippo = pkg('pippo')
pippo.risa.print_nome()
pippo.risb.print_nome()
pippo.risc.print_nome()

Output:

sono in dai lista
['a', 'b', 'c']
a
b
c

However, although this works, I would consider dynamic creating of instance attributes bad practice. Instead, you should use a dict to store these classes:

class pkg():
    def __init__(self, name):
            self.name = name
            lista_ = self.dai_lista(lista)
            print lista_
            self.ris = {}
            for i in lista_:
                    i = i.rstrip()
                    self.ris[i] = riso(i)
    def dai_lista(self, lista):
            print "sono in dai lista"
            return lista

class riso():
        def __init__(self, nome):
                self.nome = nome
        def print_nome(self):
                print self.nome

lista = ['a', 'b', 'c' ]
pippo = pkg('pippo')
pippo.ris['a'].print_nome()
pippo.ris['b'].print_nome()
pippo.ris['c'].print_nome()

And the output is the same as if you had used attributes.

Sign up to request clarification or add additional context in comments.

Comments

0

You could create a method like so:

def make_attrs(self, *lista):
    for l in lista:
        setattr(self, l, None)

Where None will initialize the values for you. If you want to create key-value pairs, you can create a dictionary:

myattrs = {'k': 'v',...}

def make_attrs(self, *args, **kwargs):
    for l in args:
        setattr(self, l, None)
    for k,v in kwargs.items():
        setattr(self, k, v)

It's generally better practice to do this in the __init__ method (I think it's a PEP standard, SO can keep me honest here), but that's a kind of hacky way to do it

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.