Pages

vendredi 21 mai 2010

Inheritance in python classes

Today I learned a few more things about functions, classes and modules in python.
Here is some notes about the inheritance in python classes. Good tutorial link is
http://docs.python.org/tutorial/classes.html.

1) simple inheritance
class DerivedClassName(BaseClassName):
statement-1
statement-N

or,
class DerivedClassName(modname.BaseClassName):

For example,
class cartesian:
def __init__(self, x=0, y=0):
self.x, self.y = x, y
def distanceToOrigin(self):
return floor(sqrt(self.x**2 + self.y**2))
class manhattan:
def __init__(self, x=0, y=0):
self.x, self.y = x, y
def distanceToOrigin(self):
return self.x + self.y

can be modified as:
class point:
def __init__(self, x=0, y=0):
self.x, self.y = x, y

class cartesian(point):
def distanceToOrigin(self):
return floor(sqrt(self.x**2 + self.y**2))
class manhattan(point):
def distanceToOrigin(self):
return self.x + self.y


2) multiple inheritance
Python supports a limited form of multiple inheritance as well. A class definition with multiple base classes looks like this:
class DerivedClassName(Base1, Base2, Base3):
statement-1
statement-N

Aucun commentaire:

Enregistrer un commentaire