0

let's say we have the following class Boy:

class Boy():

def __init__(self, name, hair, friend=None):
    self.name = name
    self.hair = hair
    self.friend = friend

and we have some instances of this class and we want to iterate it, and change attributes on these instances while iterating. for example:

ben = Boy("Ben", "red")
sam = Boy("Sam", "black")
roger = Boy("Roger", "yellow", sam)
boys = {ben, sam}
for boy in boys:
    boy = roger.friend

The above method only change the attribute of the pointer "boy" and not the instance in the set. What's the best way to approcah this?

Walid
  • 718
  • 5
  • 13
Golden
  • 407
  • 2
  • 12
  • Does this answer your question? [Iterating over object instances of a given class in Python](https://stackoverflow.com/questions/739882/iterating-over-object-instances-of-a-given-class-in-python) – Rajat Mishra Dec 27 '20 at 22:47
  • 3
    you want `boy.friend = roger`, I think (although your precise intention isn't so clear) – Robin Zigmond Dec 27 '20 at 22:52
  • @RajatMishra the link you posted doesn't have anything to do with my question. I want to iterate over a *set* and change the instances inside it, not to iterate over an instance attributes. – Golden Dec 28 '20 at 08:23

1 Answers1

-1

For changing attribute of element in the set

Your code below assign the `ref of roger's friend to the ref of boy Actually this did nothing.

for boy in boys:
    boy = roger.friend

Here is the method to change attribute of element in a set iteratively

for boy in boys:
    boy.hair = 'green'
    boy.friend = roger

# Check results
for boy in boys:
    print('----')
    print(boy.name)
    print(boy.hair)
    print(boy.friend.name)
TropicsCold
  • 115
  • 6
  • That's not what i meant at all. I want to change the attributes of the instances inside the set.. – Golden Dec 28 '20 at 08:20