Bạn đang xem thử công khai
Đăng nhập để lưu tiến độ, làm bài tập, thảo luận và nhận phản hồi.
Basic Object-Oriented Programming
Basic Object-Oriented Programming
Review lesson. A summary of the object-oriented programming part of Module 1, for quick reference and self-checking after units 1.10 → 1.11.
Class and object
class Student:
university = "Tech Institute" # class attribute: shared by all objects
def __init__(self, name, gpa): # constructor
self.name = name # instance attribute: separate for each object
self.gpa = gpa
def status(self):
return "Honours" if self.gpa >= 3.5 else "Regular"
- A class is a blueprint; an object (instance) is a concrete entity:
anna = Student("Anna", 3.8). selfis the object that is calling the method;anna.status()is equivalent toStudent.status(anna).- Changing
anna.namedoes not affect other objects; changingStudent.universityaffects every object.
The three pillars
| Concept | Meaning | Example |
|---|---|---|
| Inheritance | A subclass reuses its parent class (an "is-a" relationship); use super() to extend | class Dog(Animal) |
| Encapsulation | Protect internal data, and change it only through methods that validate | self.__balance + deposit() |
| Polymorphism | The same method name behaves differently depending on the object | speak() of Dog, Cat |
Remember
- Distinguish instance attributes (
self.x) from shared attributes (assigned at class level). isinstance(obj, ParentClass)isTrueeven for objects of a subclass.