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.

Đăng nhập
Module 1: Fundamentals of Python Programming

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).
  • self is the object that is calling the method; anna.status() is equivalent to Student.status(anna).
  • Changing anna.name does not affect other objects; changing Student.university affects every object.

The three pillars

ConceptMeaningExample
InheritanceA subclass reuses its parent class (an "is-a" relationship); use super() to extendclass Dog(Animal)
EncapsulationProtect internal data, and change it only through methods that validateself.__balance + deposit()
PolymorphismThe same method name behaves differently depending on the objectspeak() of Dog, Cat

Remember

  • Distinguish instance attributes (self.x) from shared attributes (assigned at class level).
  • isinstance(obj, ParentClass) is True even for objects of a subclass.