Set - 4

Question 1 :

What is self?

Answer :

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).


Question 2 :

How do I check if an object is an instance of a given class or of a subclass of it?

Answer :

Use the built-in function isinstance(obj, cls). You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. isinstance(obj, (class1, class2, ...)), and can also check whether an object is one of Python's built-in types, e.g. isinstance(obj, str) or isinstance(obj, (int, long, float, complex)). 

Note that most programs do not use isinstance() on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object's class and doing a different thing based on what class it is. For example, if you have a function that does something: 

def search (obj):
if isinstance(obj, Mailbox):
# ... code to search a mailbox
elif isinstance(obj, Document):
# ... code to search a document
elif ...

A better approach is to define a search() method on all the classes and just call it:

class Mailbox:

def search(self):
# ... code to search a mailbox

class Document:

def search(self):
# ... code to search a document
obj.search()

 


Question 3 :

What is delegation? 

Answer :

Delegation is an object oriented technique (also called a design pattern). Let's say you have an object x and want to change the behavior of just one of its methods. You can create a new class that provides a new implementation of the method you're interested in changing and delegates all other methods to the corresponding method of x. 

Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase:

class UpperOut:
def __init__(self, outfile):
self.__outfile = outfile
def write(self, s):
self.__outfile.write(s.upper())
def __getattr__(self, name):
return getattr(self.__outfile, name)

Here the UpperOut class redefines the write() method to convert the argument string to uppercase before calling the underlying self.__outfile.write() method. All other methods are delegated to the underlying self.__outfile object. The delegation is accomplished via the __getattr__ method; consult the language reference for more information about controlling attribute access.

Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a __settattr__ method too, and it must do so carefully. The basic implementation of __setattr__ is roughly equivalent to the following:

class X:
...
def __setattr__(self, name, value):
self.__dict__[name] = value
...

Most __setattr__ implementations must modify self.__dict__ to store local state for self without causing an infinite recursion.


Question 4 :

How do I call a method defined in a base class from a derived class that overrides it?

Answer :

If you're using new-style classes, use the built-in super() function: 

class Derived(Base):
def meth (self):
super(Derived, self).meth()

If you're using classic classes: For a class definition such as class Derived(Base): ... you can call method meth() defined in Base (or one of Base's base classes) as Base.meth(self, arguments...). Here, Base.meth is an unbound method, so you need to provide the self argument.


Question 5 :

How can I organize my code to make it easier to change the base class? 

Answer :

You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use.

Example:

BaseAlias = <real base class>
class Derived(BaseAlias):
def meth(self):
BaseAlias.meth(self)

 


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"
else:
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__':
main()
__import__('x.y.z') returns 
Try:
__import__('x.y.z').y.z

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
reload(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?!

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 math.py (socket.py, regex.py, 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