Programming with Python · free preview
Classes and Objects
Define classes that bundle data with behavior, create independent instances, and extend existing classes by inheritance.
1. Overview
Overview
2. Grouping Data in Objects
Grouping Data in Objects
3. Giving Objects Behavior
Giving Objects Behavior
4. Every Instance Is Independent
Every Instance Is Independent
5. Inheriting Behavior
Inheriting Behavior
6. A Rectangle Class
A Rectangle Class
7. Extend the Rectangle
Extend the Rectangle
8. Explain self passing
If Patient.report(patient) and patient.report() are equivalent, what is self in def report(self):?
9. Trace objects, methods, independence, and inheritance
Follow the complete object example from construction to extension.
Example. Trace objects, methods, independence, and inheritance
Problem. Follow the complete object example from construction to extension.
Correct solution.
Step 1, define the parent class and method.
class Patient:
def __init__(self, name, weight_kg, height_m):
self.name = name
self.weight_kg = weight_kg
self.height_m = height_m
def bmi(self):
return self.weight_kg / (self.height_m ** 2)Step 2, create two independent instances.
alice = Patient('Alice', 65.0, 1.70)
bob = Patient('Bob', 81.0, 1.80)
bob.weight_kg = 79.5
print(alice.name, round(alice.bmi(), 1))
print(bob.name, round(bob.bmi(), 1))Output.```output Alice 22.5 Bob 24.5
Reasoning, each constructor stores data on a separate object, so changing `bob.weight_kg` affects only Bob.
Step 3, extend without rewriting.
```python
class ClinicPatient(Patient):
def __init__(self, name, weight_kg, height_m, clinic):
super().__init__(name, weight_kg, height_m)
self.clinic = clinic
def report(self):
return f'{self.name} has BMI {self.bmi():.1f}'
carol = ClinicPatient('Carol', 70.0, 1.75, 'north')
print(carol.report())
print(carol.clinic)
print(isinstance(carol, Patient))Output.``output Carol has BMI 22.9 north True ``
Reasoning,super().__init__ runs the parent setup first, then the subclass adds clinic and a method.
关键提醒。
A constructor stores starting data on self; methods read that data; subclasses extend with super().__init__.
10. Retrieval practice
Use this new input without looking back, obj = Patient('Dan', 60.0, 1.75). Explain the difference between obj.bmi() and Patient.bmi(obj), give the exact value of round(obj.bmi(), 1), and say what happens if self is omitted from the method definition.
Give the equivalence, exact value, and consequence.
11. Mastery check
Apply class design to a new requirement, create BloodPressure storing systolic and diastolic values with a mean() method, then create HighBloodPressure adding severity() that returns high when systolic is at least 140 and normal otherwise. Give code and exact output for p = HighBloodPressure(145.0, 90.0).
Give class code and exact output.
Practice this interactively
Free account · instant grading · spaced review that schedules itself.
Start this course for free