Python OOP技术大揭秘:10个精选代码实例助你轻松掌握面向对象编程

在编程的世界里,面向对象编程(OOP)是一种强大的编程范式,它能够帮助我们更好地组织和管理代码,提高代码的可重用性和可维护性。Python作为一门功能强大的编程语言,自然少不了对OOP的支持。今天,我们就来一起探讨Python中的10个OOP技术,并通过代码实例来加深理解。
面向对象编程(Object-Oriented Programming, OOP)在Python中是非常核心的概念。以下是一些Python OOP技术的代码示例,涵盖了类的定义、继承、封装、多态和抽象等基本概念:

1. 类的定义与初始化 (init 方法)

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        pass

dog = Animal("Rex")
print(dog.name)  # 输出: Rex

2. 继承 (Inheritance)

class Dog(Animal):
    def speak(self):
        return self.name + " says Woof!"

d = Dog("Max")
print(d.speak())  # 输出: Max says Woof!

3. 封装 (Encapsulation) - 使用私有属性

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # 私有属性

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient funds")

    def get_balance(self):
        return self.__balance

account = BankAccount(100)
account.deposit(50)
print(account.get_balance())  # 输出: 150

4. 多态 (Polymorphism) - 通过继承和重写方法实现

class Cat(Animal):
    def speak(self):
        return self.name + " says Meow!"

animals = [Dog("Buddy"), Cat("Whiskers")]

for animal in animals:
    print(animal.speak())
    # 输出:
    # Buddy says Woof!
    # Whiskers says Meow!

5. 抽象基类 (Abstract Base Classes - ABC)

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

c = Circle(5)
print(c.area())  # 输出: 78.5

6. 类方法 (Class Methods) 和 静态方法 (Static Methods)

class Date:
    @classmethod
    def from_string(cls, date_str):
        return cls(*map(int, date_str.split('-')))

    @staticmethod
    def is_valid_date(date_str):
        try:
            _ = map(int, date_str.split('-'))
            return True
        except ValueError:
            return False

date_str = "2023-04-01"
if Date.is_valid_date(date_str):
    d = Date.from_string(date_str)
    print(d)

7. 属性装饰器 (@property)

class Celsius:
    def __init__(self, temperature=0):
        self._temperature = temperature

    @property
    def temperature(self):
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        if value < -273.15:
            raise ValueError("Temperature below -273.15 is not possible")
        self._temperature = value

c = Celsius()
c.temperature = 37
print(c.temperature)  # 输出: 37

8. 迭代器协议 (Iterator Protocol)

class CountDown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for num in CountDown(5):
    print(num)  # 输出: 5, 4, 3, 2, 1

9. 上下文管理器 (with 语句)

class ManagedResource:
    def __enter__(self):
        print("Resource acquired.")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Resource released.")

with ManagedResource() as resource:
    print("Doing work with the resource.")

10. 数据类 (dataclass) - Python 3.7+ 提供的简化类定义

from dataclasses import dataclass

@dataclass
class InventoryItem:
    name: str
    quantity: int
    price: float

item = InventoryItem('Widget', 100, 49.99)
print(item)  # 输出: InventoryItem(name='Widget', quantity=100, price=49.99)

这些例子覆盖了Python中OOP的核心概念,帮助理解如何在实际编程中应用这些技术。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值