Hi,

I was pondering this earlier and wasn't sure if it was possible. Say, for example you had 2 objects; spam and eggs, and you wanted to create a function to change attributes - e.g. colour.

So spam.colour = 'Blue' and eggs.colour = 'Green'. How would you change that attribute using a nice elegant function? An example of my thinking is below (I know it won't work, but hopefully you get my drift).

def changeColour(objName, colour):
[INDENT]objName.colour=colour[/INDENT]

I want to be able to change the attribute like this:

changeColour(spam, 'Blue')

This is probably a daft question, and I apologise for my explaining skills. Thanks for your patience :P

Thanks in advance :)

No, you can do it. Here's some proof

class C:
  def __init__(self,color='white'):
    self.color = color

class B: pass

def changeColor(item,color):
  try:
    print("Change color from %s to %s"%(item.color,color))
  except:
    print("Add color %s"%(color))
  item.color = color

a = C()
b = C('black')
c = B()

print('a: %s'%(a.color))
print('b: %s'%(b.color))
try:
  print('c: %s'%(c.color))
except:
  print("c has no color")

changeColor(a,'green')
changeColor(b,'purple')
changeColor(c,'brown')

print('a: %s'%(a.color))
print('b: %s'%(b.color))
print('c: %s'%(c.color))
"""output:
a: white
b: black
c has no color
Change color from white to green
Change color from black to purple
Add color brown
a: green
b: purple
c: brown
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.