Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2 instances of one class share their variables? 1

Status
Not open for further replies.

LaundroMat

Programmer
Dec 2, 2003
67
0
0
BE
I don't understand why this code
Code:
class player:

    name = ''
    hand = []

    def __init__(self, name=""):
        self.name = name

class test:
    def addItem(self, recipient, item):
        recipient.hand.append(item)

def main():
    me = player("LaundroMat")
    him = player("Someone else")

    t = test()
    t.addItem(me, "Apple")

    print him.hand
      

if __name__ == "__main__":
    main()

results in
Code:
['Apple']

It appears by calling another classes method, the list is shared?
 
I'm just learning python myself, but I think your problem is that the attribute is not created as part of the __init__. This appears to work the way you want:
Code:
class player:

    name = ''


    def __init__(self, name=""):
        [red]self.name = name[/red]
        self.hand = []

class test:
    def addItem(self, recipient, item):
        recipient.hand.append(item)

def main():
    me = player("LaundroMat")
    him = player("Someone else")

    t = test()
    t.addItem(me, "Apple")

    print him.hand
      

if __name__ == "__main__":
    main()[/code

[red][i]"... isn't sanity really just a one trick pony anyway?!  I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/i][/red]
 
Sorry for the late reply, but thanks! It works.

Maybe the Python docs should be a bit more explicit about this.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top