Skip to content

Python 面向对象编程

TIP

Python 通过类(Class)支持面向对象编程,封装了数据和操作数据的方法。

定义类

python
class Student:
    school = "第一中学"

    def __init__(self, name, age):
        self.name = name
        self.__score = 0

    def study(self, hours):
        print(f"{self.name} 学习了 {hours} 小时")

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, value):
        if 0 <= value <= 100:
            self.__score = value

s = Student("张三", 18)
s.study(2)
s.score = 95

继承

python
class Animal:
    def speak(self):
        pass

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

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

animals = [Dog(), Cat()]
for a in animals:
    print(a.speak())

魔法方法

python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"《{self.title}》- {self.author}"

    def __len__(self):
        return len(self.title)