Chapter 12 Classes

12.7 InheritanceΒΆ

Types have hierarchies. For example, both dogs and wolfs are sub categories of the canine category. Since all canines have a head, four legs and a tail, definition of these attributes would be unnecessary for dogs and wolfs given that they are sub categories of the canines. The concept of class extension comes from this observation. If a class describes a specific sub type of a general type, and a slight modification of the general type is sufficient for specifying the sub type, then inheriting attributes and methods from the general class and writing only the difference in the new class will reduce code duplication.

To facilitate description, a final version of the Account class is as follows:

class Account:
    total =100001
    def __init__(self, name, balance=0):
        self.name=name
        self.balance=balance
        self.number=Account.total
        Account.total+=1

    def deposit(self , amount):
        if amount <=0:
            print ('Error , negative amount.')
            return
        self.balance+=amount

    def withdraw(self, amount):
        if amount <0:
            print ('Error: negative amount')
            return
        if amount >self.balance:
            print ('Error: insufficient fund')
            return
        self.balance -=amount

    def __str__(self):
        return '''Account holder name: %s
            Account number: %d
            Balance: %.2f ''' %(self.name, self.number, self. balance)

Two changes are made to the Account class in this version. First, the deposit method now checks whether the amount is negative, in which case an error is reported and the deposit action is cancelled.

Second, a withdraw method is added to the class, which takes a single argument that specifies an amount, and deduces it from the balance. The withdraw method checks both whether the input amount is negative and whether it is larger than the current balance; in both cases errors are reported and the withdraw action is cancelled.

© Copyright 2024 GS Ng.

Next Section - 12.8 Sub Classes