Python3 面向objectprogrammingtutorial

Learning Python3 in class, object, inheritance, polymorphismetc.面向objectprogrammingcore concepts

面向objectprogrammingIntroduction

面向objectprogramming (Object-Oriented programming, 简称OOP) is aprogramming范式, 它将data and operationdata methodencapsulation in 一起, 形成object. in Pythonin, 一切皆object, 这使得Python成 for 一种非常适合面向objectprogramming language.

面向objectprogramming core conceptsincluding:

classes and objects

定义class

in Pythonin, usingclass关键字定义class. class名通常using驼峰命名法 (首字母 big 写) .

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

in on 面 例子in, 我们定义了一个Personclass, 它 has 两个property: name and age, 以及一个method: greet().

__init__method is a 特殊 method, 当creationclass instance时会自动调用, 用于初始化object property.

creationobject

要creationclass instance (object) , 只需调用class名并传入必要 parameter.

# creationPersonclass instance
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)

# 访问object property
print(person1.name)  # 输出: Alice
print(person2.age)   # 输出: 25

# 调用object method
person1.greet()  # 输出: Hello, my name is Alice and I'm 30 years old.
person2.greet()  # 输出: Hello, my name is Bob and I'm 25 years old.

inheritance

inheritance is 面向objectprogrammingin 一个 important concepts, 它允许我们creation一个 new class, inheritance现 has class property and method. 被inheritance class称 for 父class ( or 基class) , new creation class称 for 子class ( or forkclass) .

class Student(Person):
    def __init__(self, name, age, student_id):
        # 调用父class __init__method
        super().__init__(name, age)
        self.student_id = student_id
    
    def study(self):
        print(f"Student {self.name} (ID: {self.student_id}) is studying.")

in on 面 例子in, Studentclassinheritance了Personclass property and method, 并添加了自己 propertystudent_id and methodstudy().

# creationStudentclass instance
student = Student("Charlie", 20, "S12345")

# 访问inheritance property
print(student.name)  # 输出: Charlie
print(student.age)   # 输出: 20

# 访问自己 property
print(student.student_id)  # 输出: S12345

# 调用inheritance method
student.greet()  # 输出: Hello, my name is Charlie and I'm 20 years old.

# 调用自己 method
student.study()  # 输出: Student Charlie (ID: S12345) is studying.

polymorphism

polymorphism is 面向objectprogrammingin 另一个 important concepts, 它允许不同class object for 相同 method调用做出不同 response.

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

class Cow(Animal):
    def speak(self):
        return "Moo!"

# polymorphism 例子
def animal_sound(animal):
    print(animal.speak())

# creation不同 动物object
dog = Dog()
cat = Cat()
cow = Cow()

# 调用相同 function, 传入不同 object
animal_sound(dog)  # 输出: Woof!
animal_sound(cat)  # 输出: Meow!
animal_sound(cow)  # 输出: Moo!

in on 面 例子in, 我们定义了一个Animal基class and 三个子class: Dog, Cat and Cow. 每个子class都重写了speak()method, implementation了自己 behavior.

然 after 我们定义了一个animal_sound()function, 它接受一个动物object并调用其speak()method. 当我们传入不同 动物object时, 虽然调用 is 相同 method, 但会得 to 不同 结果, 这就 is polymorphism 体现.

encapsulation

encapsulation is 面向objectprogrammingin 一个 important concepts, 它将object data and methodencapsulation in 一起, 隐藏 in 部implementation细节, 只 for out providing必要 interface.

in Pythonin, 我们可以using under 划线来表示property or method 访问级别:

class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner  # 公共property
        self._balance = balance  # 保护property
        self.__password = "123456"  # 私 has property
    
    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            print(f"Deposit successful. New balance: {self._balance}")
        else:
            print("Deposit amount must be positive.")
    
    def withdraw(self, amount, password):
        if password != self.__password:
            print("Invalid password.")
            return
        if amount > 0 and amount <= self._balance:
            self._balance -= amount
            print(f"Withdrawal successful. New balance: {self._balance}")
        else:
            print("Invalid withdrawal amount.")
    
    def get_balance(self):
        return self._balance
# creationBankAccountobject
account = BankAccount("Alice", 1000)

# 访问公共property
print(account.owner)  # 输出: Alice

# 尝试访问保护property (不推荐) 
print(account._balance)  # 输出: 1000

# 尝试访问私 has property (会报错) 
# print(account.__password)  # AttributeError: 'BankAccount' object has no attribute '__password'

# throughmethod访问 and modifyproperty
account.deposit(500)  # 输出: Deposit successful. New balance: 1500
account.withdraw(200, "123456")  # 输出: Withdrawal successful. New balance: 1300
print(account.get_balance())  # 输出: 1300

特殊method

Pythonin has 许 many 特殊method, 它们以双 under 划线开头 and 结尾, 用于implementationobject 特殊behavior. 这些method也被称 for 魔术method (Magic Methods) .

常用 特殊method

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __add__(self, other):
        if isinstance(other, Vector):
            return Vector(self.x + other.x, self.y + other.y)
        return NotImplemented
    
    def __eq__(self, other):
        if isinstance(other, Vector):
            return self.x == other.x and self.y == other.y
        return False
    
    def __len__(self):
        # 返回向量  long 度 (模) 
        return int((self.x ** 2 + self.y ** 2) ** 0.5)

# usingVectorclass
v1 = Vector(3, 4)
v2 = Vector(1, 2)

# using__str__method
print(v1)  # 输出: Vector(3, 4)

# using__add__method
v3 = v1 + v2
print(v3)  # 输出: Vector(4, 6)

# using__eq__method
print(v1 == v2)  # 输出: False

# using__len__method
print(len(v1))  # 输出: 5

实践case: 学生managementsystem

design一个学生managementsystem, using面向objectprogramming 思想, implementation学生information 添加, delete, modify and queryfunctions.

class Student:
    def __init__(self, student_id, name, age, grade):
        self.student_id = student_id
        self.name = name
        self.age = age
        self.grade = grade
    
    def __str__(self):
        return f"ID: {self.student_id}, Name: {self.name}, Age: {self.age}, Grade: {self.grade}"

class Studentmanagementr:
    def __init__(self):
        self.students = []
    
    def add_student(self, student):
        self.students.append(student)
        print(f"Student {student.name} added successfully.")
    
    def remove_student(self, student_id):
        for student in self.students:
            if student.student_id == student_id:
                self.students.remove(student)
                print(f"Student with ID {student_id} removed successfully.")
                return
        print(f"Student with ID {student_id} not found.")
    
    def update_student(self, student_id, **kwargs):
        for student in self.students:
            if student.student_id == student_id:
                for key, value in kwargs.items():
                    if hasattr(student, key):
                        setattr(student, key, value)
                print(f"Student with ID {student_id} updated successfully.")
                return
        print(f"Student with ID {student_id} not found.")
    
    def search_student(self, student_id):
        for student in self.students:
            if student.student_id == student_id:
                print(student)
                return
        print(f"Student with ID {student_id} not found.")
    
    def display_all_students(self):
        if not self.students:
            print("No students found.")
            return
        print("All students:")
        for student in self.students:
            print(student)

# test学生managementsystem
manager = Studentmanagementr()

# 添加学生
manager.add_student(Student("S123", "Alice", 18, "A"))
manager.add_student(Student("S124", "Bob", 19, "B"))
manager.add_student(Student("S125", "Charlie", 17, "A"))

# 显示所 has 学生
print("\nDisplaying all students:")
manager.display_all_students()

# 搜索学生
print("\nSearching for student S124:")
manager.search_student("S124")

# update学生
print("\nUpdating student S124:")
manager.update_student("S124", grade="A")

# 显示所 has 学生
print("\nDisplaying all students after update:")
manager.display_all_students()

# delete学生
print("\nRemoving student S125:")
manager.remove_student("S125")

# 显示所 has 学生
print("\nDisplaying all students after removal:")
manager.display_all_students()

互动练习

练习1: creation一个graph书class

creation一个Bookclass, package含以 under property and method:

  • property: 书名 (title) , 作者 (author) , 出版年份 (year) , 价格 (price)
  • method:
    • __init__: 初始化method
    • __str__: 返回graph书information string
    • get_age: 返回graph书 年龄 (当 before 年份减去出版年份)
    • discount: application折扣, parameter for 折扣百分比

然 after creation几个graph书object, test这些method.

练习2: creation一个形状class层次structure

creation一个形状class层次structure, package含以 under class:

  • Shape: 基class, package含一个areamethod (返回0)
  • Rectangle: 矩形class, inheritance自Shape, package含宽度 (width) and high 度 (height) property, 重写areamethod
  • Circle: 圆形class, inheritance自Shape, package含半径 (radius) property, 重写areamethod
  • Triangle: 三角形class, inheritance自Shape, package含底edge (base) and high 度 (height) property, 重写areamethod

然 after creation这些形状 object, testareamethod.

练习3: creation一个购物车class

creation一个购物车classsystem, package含以 under class:

  • Product: 产品class, package含名称 (name) , 价格 (price) and 数量 (quantity) property
  • ShoppingCart: 购物车class, package含以 under method:
    • add_product: 添加产品 to 购物车
    • remove_product: from 购物车移除产品
    • update_quantity: update产品数量
    • calculate_total: 计算购物车总金额
    • display_items: 显示购物车in 所 has 产品

然 after test购物车 各种functions.