user58925
user58925

Reputation: 1633

Python Created Object Attribute

I would like to create attributes of an object based on a dictionary passed in as an argument. Here is the code. But it does not work as

class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for k in di.keys():
            name = 'k' + '_' + 'series'
            self.name = None

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series 

I get the following error: 'Obj' object has no attribute 'c'

The code read "name" as a literal, and not as the variable defined.

Upvotes: 0

Views: 40

Answers (2)

ems
ems

Reputation: 990

This is what will work :

class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for key, value in di.items():
            key += '_series'
            setattr(self, key, value)

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series

Upvotes: 0

FHTMitchell
FHTMitchell

Reputation: 12147

Use setattr

class Obj(object):
    def __init__(self, di):
        for key, value in di.items():
            setattr(self, key, value)

Some additional advice:

Your code is very strange. I'm not sure why you expect self.name to evaluate as self.(eval('name')) when that clearly doens't happen elsewhere in python

 lower = str.upper
 str.lower('Hello')  # -> still returns 'hello'

There is no need to iterate over dictionary.keys(), especially in python 2. for k in dictionary: works just fine. If you want both keys and values use dictionary.items() (or dictionary.iteritems() in python 2).

name = 'k' + '_' + 'series' just makes the string 'k_series'. You need to be able to tell the difference between a string and a variable name. I think you mean k + '_' + series but series is never defined. Don't use + to concatenate strings like that anyway, use .format.

Upvotes: 2

Related Questions