Default argument to __init__
Hi All: Here's a piece of Python code and it's output. The output that Python shows is not as per my expectation. Hope someone can explain to me this behaviour: [code] class MyClass: def __init__(self, myarr=[]): self.myarr = myarr myobj1 = MyClass() myobj2 = MyClass() myobj1.myarr += [1,2,3] myobj2.myarr += [4,5,6] print myobj1.myarr print myobj2.myarr [/code] The output is: [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] Why do myobj1.myarr and myobj2.myarr point to the same list? The default value to __init__ for the myarr argument is [], so I expect that every time an object of MyClass is created, a new empty list is created and assigned to myarr, but it seems that the same empty list object is assigned to myarr on every invocation of MyClass.__init__ It this behaviour by design? If so, what is the reason, as the behaviour I expect seems pretty logical. Thanks. Vaibhav -- http://mail.python.org/mailman/listinfo/python-list
Re: Scanning a file
I think implementing a finite state automaton would be a good (best?) solution. I have drawn a FSM for you (try viewing the following in fixed width font). Just increment the count when you reach state 5. <---| || 0 0 | 1 0 |0 -->[1]--->[2]--->[3]--->[4]--->[5]-| ^ || ^ | | | 1| |<---| | | |1 |1 |_|1 |_| | | ^ 0 | | |-|<-| If you don't understand FSM's, try getting a book on computational theory (the book by Hopcroft & Ullman is great.) Here you don't have special cases whether reading in blocks or reading whole at once (as you only need one byte at a time). Vaibhav -- http://mail.python.org/mailman/listinfo/python-list
Re: Scanning a file
Steve Holden wrote: > Indeed, but reading one byte at a time is about the slowest way to > process a file, in Python or any other language, because it fails to > amortize the overhead cost of function calls over many characters. > > Buffering wasn't invented because early programmers had nothing better > to occupy their minds, remember :-) Buffer, and then read one byte at a time from the buffer. Vaibhav -- http://mail.python.org/mailman/listinfo/python-list
Re: altering an object as you iterate over it?
bruno at modulix wrote: > fin = open(path, 'r') > fout = open(temp, 'w') > for line in fin: > if line.strip(): > fout.write(line) > fin.close() > fout.close() > > then delete path and rename temp, and you're done. And yes, this is > actually the canonical way to do this !-) What if there's a hard link to path? -- Vaibhav -- http://mail.python.org/mailman/listinfo/python-list
