2

Let's say I have the following in Python:

class Test():
    self.value1 = 1
    self.value2 = 2

def setvalue1(self, value):
    self.value1 = value

So one can set up value1 by doing:

Test.setvalue1('Hola')

or

Test.Value1 = 'Hola'

So far so good. My problem is I would like to set the values by reading them somewhere else so for instance I could have the following:

A = [['Value1','Hola'],['Value2','Adios']]

I would like to be able to run something that will do (in pseudo code):

for each in A:
    Test.each[0] = A[1]

Is this possible? Thanks so much!

Yona
  • 571
  • 7
  • 23

2 Answers2

2

You could do it like that:

class Test:

    def __init__(self):
        self.val1 = 1



t = Test()
setattr(t, 'val2', 2)

print t.val2

Or like that:

class Test:

    def __init__(self):
        self.val1 = 1

    def setself(self, name, val):
        self.__dict__[name] = val

t = Test()
t.setself('val3', 3)

print t.val3
Maresh
  • 4,644
  • 25
  • 30
1

Iterate over your data structure and use setattr() on an instance of your class Test:

test = Test()

data = [('Value1', 'Hola'), ('Value2', 'Adios']
for k, v in data:
    setattr(test, k, v)

This kind of data structure btw is generally considered a "key/value" pair and you could use a Python dictionary (dict) here.

Example:

test = Test()

data = {"value1": "Hola", "Value2": "Adios"}
for k, v in data.items()
    setattr(test, k, v)

Now let's fix up your Test class:

class Test(object):

    def __init__(self):
        self.value1 = 1
        self.value2 = 2

    def setvalue1(self, value):
        self.value1 = value
James Mills
  • 18,669
  • 3
  • 49
  • 62
  • 1
    In which way is adding useless properties a "fix" ? The only broken things in the OP's class were indentation and the lack of the `__init__` method (or more exactly what should have been in the `__init__` method directly at the class level). – bruno desthuilliers May 29 '15 at 12:55
  • @brunodesthuilliers You are quite right; I've removed the useless properties :) – James Mills May 29 '15 at 13:01