Lecture16 Inheritance
一. Attributes
- Looking Up Attributes by Name
<expression> . <name>
To evaluate a dot expression:
- Evaluate the 《expression》 to the left of the dot, which yields the object of the dot expression
- 《name》 is matched against the instance attributes of that object; if an attribute with that name exists, its value is returned
- If not, 《name》 is looked up in the class, which yields a class attribute value
- That value is returned unless it is a function, in which case a bound method is returned instead
- Class Attributes
Class attributes are “shared” across all instances of a class because they are attributes of the class, not the instance
二、Attribute Assignment
• If the object is aninstance, then assignment sets an instance attribute
• If the object is a class, then assignment sets a class attribute
举例:
三、Inheritance
- Looking Up Attribute Names on Classes
规则:
To look up a name in a class:
<1> If it names an attribute in the class, return the attribute value.
<2> Otherwise, look up the name in the base class, if there is one.
四、Object-Oriented Design
-
Designing for Inheritance
-
Inheritance and Composition
Inheritance is best for representing is-a relationships
• E.g., a checking account is a specific type of account
• So, CheckingAccount inherits from Account
Composition is best for representing has-a relationships
• E.g., a bank has a collection of bank accounts it manages
• So, A bank has a list of accounts as an attribute