Wednesday, September 14, 2011

python: pitfalls

http://zephyrfalcon.org/labs/python_pitfalls.html



5. Mutable default arguments


This one bites beginners over and over again. It's really a variant of #2, combined with unexpected behavior of default arguments. Consider this function:

>>> def popo(x=[]):
...     x.append(666)
...     print x
...     
>>> popo([1, 2, 3])
[1, 2, 3, 666]
>>> x = [1, 2]
>>> popo(x)
[1, 2, 666]
>>> x
[1, 2, 666]

This was expected. But now:

>>> popo()
[666]
>>> popo()
[666, 666]
>>> popo()
[666, 666, 666]

Maybe you expected that the output would be [666] in all cases... after all, when popo() is called without arguments, it takes [] as the default argument for x, right? Wrong. The default argument is bound *once*, when the function is *created*, not when it's called. (In other words, for a function f(x=[]), x is *not* bound whenever the function is called. x got bound to [] when we defined f, and that's it.) So if it's a mutable object, and it has changed, then the next function call will take this same list (which has different contents now) as its default argument.
Solution: This behavior can occasionally be useful. In general, just watch out for unwanted side effects.

Monday, September 12, 2011

prog: namespace

http://www.freenetpages.co.uk/hp/alan.gauld/tutname.htm

What is namespace?
The concept is pretty straightforward, a namespace is a space or region, within a program, where a name (variable, class etc) is valid. 


We actually use this idea in everyday life. Suppose you work in a big company and there is a colleague called Joe. In the accounts department there is another guy called Joe who you see occasionally but not often. In that case you refer to your colleague as "Joe" and the other one as "Joe in Accounts". You also have a colleague called Susan and there is another Susan in Engineering with whom you work closely. When referring to them you might say "Our Susan" or "Susan from Engineering". Do you see how you use the department name as a qualifier? That's what namespaces do in a program, they tell both programmers and the translator which of several identical names is being referred to.



##### module first.py #########
spam = 42
def print42(): print spam
###############################
##### module second.py ########
from first import *  # import all names from first

spam = 101   # create spam variable, hiding first's version
print42()    # what gets printed? 42 or 101?

################################
If you thought it would print 101 then you were wrong. A name is simply a label used to reference an object. Now in the first module the name print42 refers to the function object defined in the module. So although we imported the name into our module we did not actually import the function which still refers to its own version of spam. Thus when we created our new spam variable it has no effect on the function referred to by print42.






Friday, September 9, 2011

prog: A* c = new C( )

-

prog: OOP

http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm

Data hiding
Encapsulation
Message passing metaphor
self: this parameter is filled in by the interpreter at run-time, not by the programmer.

polymorphism: If we have two objects of different classes but which support the same set of messages but with their own corresponding methods then we can collect these objects together and treat them identically in our program but the objects will behave differently. This ability to behave differently to the same input messages is known as.. 
Polymorphism: the ability to send the same message to several different types of object and each behaves in its own particular way in response.



class BalanceError(Exception): 
      value = "Sorry you only have $%6.2f in your account"

class BankAccount:
    def __init__(self, initialAmount):
       self.balance = initialAmount
       print "Account created with balance %5.2f" % self.balance

    def deposit(self, amount):
       self.balance = self.balance + amount

    def withdraw(self, amount):
       if self.balance >= amount:
          self.balance = self.balance - amount
       else:
          raise BalanceError, BalanceError.value % self.balance

    def checkBalance(self):
       return self.balance
       
    def transfer(self, amount, account):
       try: 
          self.withdraw(amount)
          account.deposit(amount)
       except BalanceError:
          print BalanceError.value
Notice that we didn't use self when defining the value in BalanceError, that's because value is a shared attribute across all instances, it is defined at the class level and known as a class variable. 



- Class variable and Instance/Object variable.


- It doesn't save a lot of code but it does mean we only have one method definition to test and maintain instead of three identical methods. This type of programming where we introduce a superclass with shared functionality is sometimes called mixin programming and the minimal class is called a mixin class. It is a common outcome of this style that the final class definitions have little or no body but a long list of inherited classes, just as we see here.











Wednesday, September 7, 2011

comp: stack and heap

http://www.maxi-pedia.com/what+is+heap+and+stack

Stack is a section of memory and its associated registers 





  • Both the stack and the heap are memory areas allocated from the underlying operating system (often virtual memory that are mapped to physical memory on demand).
  • In a multi-threaded environment each thread will have it's own completely independent stack but they will share the heap. Concurrent access has to be controlled on the heap and is not possible on the stack.

prog: pure virtual function and abstract class

http://en.wikipedia.org/wiki/Virtual_function


pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class, if that class is not abstract. Classes containing pure virtual methods are termed "abstract"; they cannot be instantiated directly, and a subclass of an abstract class can only be instantiated directly, if all inherited pure virtual methods have been implemented by that class or a parent class. Pure virtual methods typically have a declaration (signature) and no definition (implementation).



prog: Virtual function

http://www.cplusplus.com/forum/beginner/13885/




A function should be declared virtual [in the base class] if you ever intend to allow derived classes to reimplement the function AND you intend to call the function through a base class pointer/reference.



struct Base
{
    virtual void do_something() = 0;
};


struct Derived1 : public Base
{
    void do_something()
    {
         cout << "I'm doing something";
    }
};

struct Derived2 : public Base
{
    void do_something()
    {
         cout << "I'm doing something else";
    }
};

int main()
{
    Base *pBase = new Derived1;
    pBase->do_something();//does something
    delete pBase;
    pBase = new Derived2;
    pBase->do_something();//does something else
    delete pBase;
    return 0;
}

Friday, September 2, 2011

references: Python, C/C++

http://www.cplusplus.com/reference/stl/

http://eli.thegreenplace.net/2010/09/18/python-internals-symbol-tables-part-1/


Python: Notes

- For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use reload(), e.g. reload(modulename).

- The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don’t match.

- A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded.

opcode

http://en.wikipedia.org/wiki/Opcode

Compiler

http://en.wikipedia.org/wiki/Compiler

STL Containers

 http://www.cplusplus.com/reference/stl/

Thursday, September 1, 2011

prog: language translator

 such as a compiler or interpreter

Python: Symbol table

http://eli.thegreenplace.net/2010/09/18/python-internals-symbol-tables-part-1/

In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program’s source code is associated with information relating to its declaration or appearance in the source, such as its type, scope level and sometimes its location.


A high-level view of the front-end of CPython is:
  1. Parse source code into a parse tree
  2. Transform parse tree into an Abstract Syntax Tree
  3. Transform AST into a Control Flow Graph
  4. Emit bytecode based on the Control Flow Graph
 Symbol tables are generated by the compiler from AST just before bytecode is generated. The symbol table is responsible for calculating the scope of every identifier in the code. symtable provides an interface to examine these tables.

prog: bytecode

http://en.wikipedia.org/wiki/Bytecode

Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in .pyc and .pyo files so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). This “intermediate language” is said to run on a virtual machine that executes the machine code corresponding to each bytecode. Do note that bytecodes are not expected to work between different Python virtual machines, nor to be stable between Python releases.
(http://docs.python.org/glossary.html#term-bytecode)

Python: Coding style

http://www.python.org/dev/peps/pep-0008/