Set - 4

Question 6 :

How do I create static class data and static class methods? 

Answer :

Static data (in the sense of C++ or Java) is easy; static methods (again in the sense of C++ or Java) are not supported directly. 
For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment: 
class C:

count = 0 # number of times C.__init__ called
def __init__(self):
C.count = C.count + 1
def getcount(self):
return C.count # or return self.count

c.count also refers to C.count for any c such that isinstance(c, C) holds, unless overridden by c itself or by some class on the base-class search path from c.__class__ back to C. 

Caution: within a method of C, an assignment like self.count = 42 creates a new and unrelated instance vrbl named "count" in self's own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not:

C.count = 314 

Static methods are possible when you're using new-style classes: 
class C:

def static(arg1, arg2, arg3):
# No 'self' parameter!
static = staticmethod(static)

However, a far more straightforward way to get the effect of a static method is via a simple module-level function: 

def getcount():
return C.count

If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation.

Question 7 :

How can I overload constructors (or methods) in Python? 

Answer :

This answer actually applies to all methods, but the question usually comes up first in the context of constructors. 
In C++ you'd write

class C {
	C() { cout << "No arguments\n"; }
	C(int i) { cout << "Argument is " << i << "\n"; }

in Python you have to write a single constructor that catches all cases using default arguments. For example:

class C:
def __init__(self, i=None):
if i is None:
print "No arguments"
print "Argument is", i

This is not entirely equivalent, but close enough in practice. 
You could also try a variable-length argument list, e.g. 

def __init__(self, *args):

The same approach works for all method definitions.

Question 8 :

How do I find the current module name?

Answer :

A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:

def main():
print 'Running test...'
if __name__ == '__main__':
__import__('x.y.z') returns 

For more realistic situations, you may have to do something like

m = __import__(s)
for i in s.split(".")[1:]:
m = getattr(m, i)


Question 9 :

When I edit an imported module and reimport it, the changes don't show up. Why does this happen?

Answer :

For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn't, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force rereading of a changed module, do this:

import modname

Warning: this technique is not 100% fool-proof. In particular, modules containing statements like

from modname import some_objects

will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will not be updated to use the new class definition. This can result in the following paradoxical behavior:

>>> import cls
>>> c = cls.C() # Create an instance of C
>>> reload(cls)
<module 'cls' from 'cls.pyc'>
>>> isinstance(c, cls.C) # isinstance is false?!

The nature of the problem is made clear if you print out the class objects:

>>> c.__class__
<class cls.C at 0x7352a0>
>>> cls.C
<class cls.C at 0x4198d0>


Question 10 :

Where is the (,, etc.) source file?

Answer :

There are (at least) three kinds of modules in Python: 
1. modules written in Python (.py);
2. modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
3. modules written in C and linked with the interpreter; to get a list of these, type:

import sys
print sys.builtin_module_names