You are not logged in.
I have a class:
1 class Node:
2 __value = ""
3 __others = []
4 def __init__(self):
5 self.__value = ""
6 def set(self, n):
7 self.__value = n
8 def get(self):
9 return self.__value
10 def connect(self, n):
11 self.__others.append(n)
12 def add(self, n):
13 tmp = Node()
14 tmp.set(n)
15 self.connect(tmp)
16 def show(self):
17 print self.get()
18 print "-> ",
19 for i in self.__others:
20 print i.get()
21 print " ",
22 print ""
23 def go(self, n):
24 for i in self.__others:
25 if n == i.get():
26 return i
27 print "error: no results"
which attempts to be a network of interconnected nodes (each with a dynamic number of connections). The problem is that the __others list seems to be global amoungst all instances of Node.
Is there any way of getting around this?
Last edited by Lexion (2009-10-14 14:33:38)
urxvtc / wmii / zsh / configs / onebluecat.net
Arch will not hold your hand
Offline
You can't initialize instance variables in a class directly -- you have to do it in the constructor. That is,
1 class Node:
2 __value = ""
3 __others = []
initializes the variables Node.__others and Node.__value, not attributes of any instance. Your problem is probably that you don't initialize self.__others in the constructor. When you call an append() on self.__others, Python looks in the `self' object for an attribute called __others, and doesn't find it. So it moves up one level and looks in the Node class for such an attribute, finds it, and changes it. This doesn't happen with self.__value, because self.__value is a different object from Node.__value due to the fact that you changed it in the constructor.
OT: is there a particular reason for using `__value' and `__others' instead of just `value' and `others'?
Offline
To put a name to it __value and __others are class variables.
http://www.ibiblio.org/g2swap/byteofpyt … -vars.html
This probably explains the use of double underscores.
http://docs.python.org/tutorial/classes … -variables
Offline
I'm aware of the effects of leading-double-underscore names in Python. I was just wondering why in this particular instance the OP would specifically want this behavior. Unless you want to avoid conflict with an attribute of a superclass, the name-mangling doesn't offer any features of value.
Offline
Just so that you are aware, because this is the most common cause of trouble I see with people learning Python. You are using old style classes, which are in there for reverse compatability. You probably don't mean to use them.
# old style
class Node:
pass
# new syle
class Node(object):
pass
Lots of awesome features like attribute properties and decorators only work with new style classes.
To answer your question, you should have the variables in __init__, unless you want them to be global to the class.
Offline
Thanks, I got it.
urxvtc / wmii / zsh / configs / onebluecat.net
Arch will not hold your hand
Offline