Python bug???

Started by
6 comments, last by Joviex 13 years, 9 months ago
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]
Advertisement
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
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]
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?
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
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.
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.
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)

This topic is closed to new replies.

Advertisement