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):

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):
    print("Change color from %s to %s"%(item.color,color))
    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))
  print('c: %s'%(c.color))
  print("c has no color")


print('a: %s'%(a.color))
print('b: %s'%(b.color))
print('c: %s'%(c.color))
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

Edited 5 Years Ago by griswolf: n/a

This question has already been answered. Start a new discussion instead.