Python is a new age language when compared to good old C. Writing code in Python needs a subtle shift from C mindset. Python offers so many things ready-made that make you feel that you wrote very less code. Anyway, I goofed up while using a very common feature of C: pass by reference.
Python too offers it, but with a caveat: you should know mutable and immutable data objects. When you pass a mutable object like list, dictionary; they can be changed. But, if you pass an immutable data object like string, tuple; they are kept unchanged in caller’s scope. This is very similar to passing “references” (C++) or constant pointers.
1 class Node: 2 def __init__(self, value, data=[]): 3 self.char = value 4 # We intend to keep a list of values for a key 5 self.data = data 6 # XXX: List of Node 7 self.children = [] 8 9 10 n = Node('a') 11 m = Node('b') 12 13 (n.data).append("north") 14 (m.data).append("south") 15 16 print n.data 17 print m.data
The output of the above code is:
ubuntu@ubuntu:~/Desktop/ToKeep/cprogs/pycon$ python pybug.py ['north', 'south'] ['north', 'south']
I don’t quite understand why Python keeps a single instance of default argument(list). Nonetheless, it is interesting.
This thread on Stackoverflow is very informational.
-
Omitting “this” pointer
In C++, “this” which is pointer to the object is passed implicitly. Python has similar keyword “self” for this. But, contrary to an implicit understanding, “self” should be an argument to a function, else you would see an error:
NameError: global name ‘self’ is not defined
1 class pydbg: 2 def __init__(self, modname=None): 3 self.level = 0 4 self.modname = modname 5 6 def DLOG(self, lvl=None, fmt=None, *args): 7 self.level = lvl 8 print '%s' %self.modname 9 print fmt 10 for arg in args: 11 print arg
So, always add the “self” argument while adding a function in your class.
This is the right way to achieve what you want 🙂
class Node:
def __init__(self, value):
self.char = value
self.data = []
self.children = []
n = Node(‘a’)
m = Node(‘b’)
n.data.append(‘South’)
m.data.append(‘North’)
print n.data
print m.data
Output:
C:\Chetan\Python25>c:\python25\python pybug.py
[‘South’]
[‘North’]
LikeLike
hey Chetan,
Your answer is right. I think Python optimized and avoid creating a new list for second object.
Thanks for dropping by!
LikeLike