Skip to main content
GameDev.net gamedev.net
🔒 Locked

Python bug???

Started by macktruck6666 Jul 14, 2010 at 10:14 PM 6 replies 2.6k views
Original Post
macktruck6666
macktruck6666
The problem is that I expect the output to be:
0
0
instead it is:
0
1

Is there a solution to the following code?

class Menu:   subMenuList = []   def addSubMenu(self, newSubMenu):      print len(newSubMenu.subMenuList)      self.subMenuList.append(newSubMenu)      print len(newSubMenu.subMenuList)mainMenu = Menu()subMenu = Menu()mainMenu.addSubMenu(subMenu)


[Edited by - macktruck6666 on July 14, 2010 10:34:48 PM]
Roboguy
Roboguy
append adds a new element to the list, which, in this case, is [].
So the list looks like this after the append: [[]]. That's a list containing one element; the one element being [].
Also, you can use the [code] and tags in the forums to preserve indentation. Look here: GDNet Forums FAQ
macktruck6666
macktruck6666
The item that is added is actually a menu object. I've tested it.
So, mainMenu.subMenuList looks like [menu object]
and, subMenu.subMenuList looks like [menu object]
and, subMenu.subMenuList[0].subMenuList[0].subMenuList looks like [menu object]
Sneftel
Sneftel
Riight? So after the append, newSubMenu.subMenuList contains one item. Forget the nesting hoohah -- why would you expect a list to be empty, when you just put something in it?
macktruck6666
macktruck6666
I put something into Main.subMenuList not into subMenu.subMenuList
or in context of addSubMenu method
I put something into self.subMenuList not into self.subMenuList[0].subMenuList
Oluseyi
Oluseyi
Quote:
Original post by macktruck6666
I put something into Main.subMenuList not into subMenu.subMenuList
or in context of addSubMenu method
I put something into self.subMenuList not into self.subMenuList[0].subMenuList

Wrong.
Hodgman
Hodgman
Ah, I didn't understand what was going on here either.

So if I debluntize Ollies reply, the subMenuList member doesn't actually belong to either of the Menu objects; it belongs to the Menu class and is therefore shared by both objects.
Joviex
Joviex
Quote:
Original post by Hodgman
Ah, I didn't understand what was going on here either.

So if I debluntize Ollies reply, the subMenuList member doesn't actually belong to either of the Menu objects; it belongs to the Menu class and is therefore shared by both objects.


Correct!



class Menu:   def __init__(self):      self.subMenuList = []   def addSubMenu(self, newSubMenu):      print len(newSubMenu.subMenuList)      self.subMenuList.append(newSubMenu)      print len(newSubMenu.subMenuList)mainMenu = Menu()subMenu = Menu()mainMenu.addSubMenu(subMenu)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.