Introducing Python © Chirag Wazir 2002 Prev   Index   Next

Classes

self is used explicitly

__init__, __del__
__str__, __lt__, __eq__, __getattr__, __setattr__, __len__
__getitem__, __setitem__, __iter__, __contains__
__add__, __sub__, ....

__var for mangling private names

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def show(self):
        print self.name, 'is', self.age, 'years old'

class Employee(Person):
    def __init__(self, name, age, salary):
        Person.__init__(self, name, age)
        self.salary = salary
    def after_tax(self):
        return int(self.salary * 0.85)

p = Person('Mark', 25)
p.show()
e = Employee('Guido', 30, 9000)
e.show()
print 'Salary after tax =', e.after_tax()
Mark is 25 years old
Guido is 30 years old
Salary after tax = 7650

Classes v/s. Instances __class__, type()

For multiple inheritance:

class DerivedClassName(Base1, Base2, Base3):

The resolution rule used for class attribute references is depth-first, left-to-right.

New style classes:

Derive from object.

The resolution rule has been changed to the Common Lisp one (to handle the diamond diagram).

See "Unifying types and classes in Python 2.2" by GvR for more information (www.python.org/2.2/descrintro.html)