Data hiding
Encapsulation
Message passing metaphor
self: this parameter is filled in by the interpreter at run-time, not by the programmer.
polymorphism: If we have two objects of different classes but which support the same set of messages but with their own corresponding methods then we can collect these objects together and treat them identically in our program but the objects will behave differently. This ability to behave differently to the same input messages is known as..
Polymorphism: the ability to send the same message to several different types of object and each behaves in its own particular way in response.
class BalanceError(Exception): value = "Sorry you only have $%6.2f in your account" class BankAccount: def __init__(self, initialAmount): self.balance = initialAmount print "Account created with balance %5.2f" % self.balance def deposit(self, amount): self.balance = self.balance + amount def withdraw(self, amount): if self.balance >= amount: self.balance = self.balance - amount else: raise BalanceError, BalanceError.value % self.balance def checkBalance(self): return self.balance def transfer(self, amount, account): try: self.withdraw(amount) account.deposit(amount) except BalanceError: print BalanceError.valueNotice that we didn't use self when defining the value in BalanceError, that's because value is a shared attribute across all instances, it is defined at the class level and known as a class variable.
- Class variable and Instance/Object variable.
- It doesn't save a lot of code but it does mean we only have one method definition to test and maintain instead of three identical methods. This type of programming where we introduce a superclass with shared functionality is sometimes called mixin programming and the minimal class is called a mixin class. It is a common outcome of this style that the final class definitions have little or no body but a long list of inherited classes, just as we see here.
No comments:
Post a Comment