Reputation: 55
is it possible to store a class instance as a new instance. For example,
class ClassName(object):
def __init__(self, **kw):
self._name = ''
self._time = float(timeString)
for attr, val in kw.items():
if val == None:
continue
setattr(self, '_' + attr, val)
def getName(self): return self._name
name = property(getName)
but lets say we store the instance in a list like so..
cl = ClassName('name1')
cl2 = ClassName('name2')
li = list()
li.append(cl)
li.append(cl2)
and then we iterate through them..
for c in li:
print( c.name )
would they have different values, or will it be the same, if so how can I give the class instances a unique id?
Upvotes: 1
Views: 73
Reputation: 3706
Using the dictionary object that tracks a class's variables, it is possible to add and remove variables of a class.
Simply pass a dictionary to the update()
method of the objects built-in dictionary, __dict__
. The key will be the variable name that is accessible from the class.
class EmptyClass:
pass
var_name = 'new_variable'
var_value = 'This variable is a test, anything can go here'
obj = EmptyClass()
obj.__dict__.update( {var_name: var_value} )
print obj.new_variable
See the add_food() function below for a real example.
class Food:
def __init__( self, name, description ):
self.name = name
self.description = description
def __str__(self): return '<Food: name=%s, description=%s' % (self.name, self.description)
class Foods:
def __init__( self, category, *foods ):
self.category = category
self.foods = {}
if foods:
self.add_foods( *foods )
def add_food( self, food, update=True ):
self.foods[food.name] = food
if update:
self.__dict__.update( {food.name.replace(' ', '_'): food} )
def add_foods( self, *foods ):
for food in foods:
# Set update to false, so an update doesn't happen
# more than once
self.add_food( food, False )
new_food = { food.name: food for food in foods }
self.__dict__.update( new_food )
apple = Food('apple', 'Round and red')
grape = Food('grape', 'small, round and purple')
# Our add_food() method handles removing the space and putting
# an underscore. Variables can't have spaces in them!
apple2 = Food('green apple', 'Round and green')
fruits = Foods('fruits', apple, grape)
print fruits.apple
print fruits.grape
fruits.add_food( apple2 )
print fruits.green_apple
print
print fruits.foods['apple']
print fruits.foods['grape']
print fruits.foods['green apple']
Upvotes: 0
Reputation: 25518
If I understand what you mean, then yes: they will have different values. Fixing the problems mentioned in the comments:
class ClassName(object):
def __init__(self, **kw):
self._name = ''
for attr, val in kw.items():
if val == None:
continue
setattr(self, '_' + attr, val)
def getName(self): return self._name
name = property(getName)
cl = ClassName(name='name1')
cl2 = ClassName(name='name2')
li = list()
li.append(cl)
li.append(cl2)
Then:
>>> li[0].name
'name1'
>>> li[1].name
'name2'
(the names you set with your keyword arguments).
Upvotes: 1