20个例题掌握Python类相关知识点

1. 定义一个简单的类

class Dog:
    def __init__(self, name):
        self.name = name
    
    def bark(self):
        print(f"{self.name} says woof!")

if __name__ == "__main__":
    my_dog = Dog("Rex")
    my_dog.bark()

2. 类的基本属性

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        print(f"Brand: {self.brand}, Model: {self.model}")

if __name__ == "__main__":
    my_car = Car("Toyota", "Corolla")
    my_car.display_info()

3. 类方法

class Circle:
    pi = 3.14
    
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return Circle.pi * self.radius * self.radius

if __name__ == "__main__":
    circle = Circle(5)
    print("Area:", circle.area())

4. 类变量和实例变量

class Employee:
    company_name = "ABC Corp"
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_employee(self):
        print(f"Name: {self.name}, Age: {self.age}, Company: {Employee.company_name}")

if __name__ == "__main__":
    emp = Employee("John", 30)
    emp.display_employee()

5. 类的继承

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        print("Animal sound")

class Dog(Animal):
    def speak(self):
        print(f"{self.name} says woof!")

if __name__ == "__main__":
    dog = Dog("Buddy")
    dog.speak()

6. 多重继承

class Walking:
    def walk(self):
        print("Walking")

class Talking:
    def talk(self):
        print("Talking")

class Robot(Walking, Talking):
    pass

if __name__ == "__main__":
    robot = Robot()
    robot.walk()
    robot.talk()

7. 使用super()调用父类方法

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print(f"Name: {self.name}, Age: {self.age}")

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

    def display(self):
        super().display()
        print(f"Student ID: {self.student_id}")

if __name__ == "__main__":
    student = Student("Alice", 20, "S12345")
    student.display()

8. 类的封装

class Account:
    def __init__(self):
        self.__balance = 0

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
        else:
            print("Invalid amount")

    def get_balance(self):
        return self.__balance

if __name__ == "__main__":
    acc = Account()
    acc.deposit(100)
    print("Balance:", acc.get_balance())

9. 静态方法

class MathOperations:
    @staticmethod
    def add(a, b):
        return a + b

if __name__ == "__main__":
    result = MathOperations.add(5, 3)
    print("Addition:", result)

10. 类方法

class Book:
    total_books = 0

    def __init__(self, title):
        self.title = title
        Book.total_books += 1
    
    @classmethod
    def get_total_books(cls):
        return cls.total_books

if __name__ == "__main__":
    book1 = Book("Python for Beginners")
    book2 = Book("Advanced Python")
    print("Total books:", Book.get_total_books())

11. 类的多态

class Shape:
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius * self.radius

if __name__ == "__main__":
    rect = Rectangle(3, 4)
    circ = Circle(5)
    shapes = [rect, circ]
    for shape in shapes:
        print("Area:", shape.area())

12. 操作符重载

class ComplexNumber:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag
    
    def __add__(self, other):
        return ComplexNumber(self.real + other.real, self.imag + other.imag)

    def __str__(self):
        return f"{self.real} + {self.imag}i"

if __name__ == "__main__":
    c1 = ComplexNumber(1, 2)
    c2 = ComplexNumber(3, 4)
    c3 = c1 + c2
    print("Sum:", c3)

13. 抽象类

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Woof")

if __name__ == "__main__":
    dog = Dog()
    dog.make_sound()

14. 私有变量和方法

class MySecret:
    def __init__(self):
        self.__secret = "hidden value"

    def reveal_secret(self):
        print("Secret:", self.__secret)

if __name__ == "__main__":
    obj = MySecret()
    obj.reveal_secret()
    # print(obj.__secret)  # This will raise an AttributeError

15. 类的组合

class Engine:
    def start(self):
        print("Engine started")

class Car:
    def __init__(self, engine):
        self.engine = engine

    def start(self):
        self.engine.start()

if __name__ == "__main__":
    engine = Engine()
    car = Car(engine)
    car.start()

16. 属性装饰器

class Temperature:
    def __init__(self, celsius):
        self.__celsius = celsius

    @property
    def fahrenheit(self):
        return (self.__celsius * 9/5) + 32

if __name__ == "__main__":
    temp = Temperature(0)
    print("Fahrenheit:", temp.fahrenheit)

17. 析构方法

class Person:
    def __init__(self, name):
        self.name = name
        print(f"Person {self.name} created")
    
    def __del__(self):
        print(f"Person {self.name} destroyed")

if __name__ == "__main__":
    p = Person("John")
    del p

18. 类的方法链调用

class Chain:
    def step_one(self):
        print("Step one")
        return self
    
    def step_two(self):
        print("Step two")
        return self
    
if __name__ == "__main__":
    obj = Chain()
    obj.step_one().step_two()

19. 自反性

class Reflexive:
    def __init__(self, value):
        self.value = value
    
    def __eq__(self, other):
        if isinstance(other, Reflexive):
            return self.value == other.value
        return False

if __name__ == "__main__":
    a = Reflexive(10)
    b = Reflexive(10)
    print("Are they equal?", a == b)

20. 类的例外处理

class NegativeAgeError(Exception):
    def __init__(self, message="Age cannot be negative"):
        self.message = message
        super().__init__(self.message)

class Person:
    def __init__(self, name, age):
        self.name = name
        if age < 0:
            raise NegativeAgeError()
        self.age = age

if __name__ == "__main__":
    try:
        p = Person("John", -1)
    except NegativeAgeError as e:
        print(e)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

superdont

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值