掌握 Python 面向对象编程 (OOP):带有示例的综合指南

掌握 python 面向对象编程 (oop):带有示例的综合指南

介绍

面向对象编程(oop)是现代软件开发中最流行的编程范例之一。它允许您使用类和对象对现实世界的实体进行建模,使代码可重用、模块化和可扩展。在这篇博文中,我们将使用单个用例示例从基础到高级探索 python 的 oop 概念:为在线商店构建库存管理系统

为什么使用面向对象编程?

  • 模块化:代码被分解为独立的模块。
  • 可重用性:一旦编写了一个类,您就可以在程序或未来项目中的任何地方使用它。
  • 可扩展性:oop 允许程序通过添加新类或扩展现有类来扩展。
  • 可维护性:更易于管理、调试和扩展。

基本概念:类和对象

什么是类和对象?

  • class:创建对象(实例)的蓝图。它定义了对象将具有的一组属性(数据)和方法(函数)。
  • object:类的实例。您可以将对象视为具有状态和行为的现实世界实体。

示例:库存项目类别

让我们首先创建一个类来表示我们在线商店库存中的商品。每件商品都有名称、价格和数量。

class inventoryitem:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity

    def get_total_price(self):
        return self.price * self.quantity

# creating objects of the class
item1 = inventoryitem("laptop", 1000, 5)
item2 = inventoryitem("smartphone", 500, 10)

# accessing attributes and methods
print(f"item: {item1.name}, total price: ${item1.get_total_price()}")

说明

  • __init__方法是构造函数,用于初始化对象的属性。
  • self 指的是类的当前实例,允许每个对象保持自己的状态。
  • 方法 get_total_price() 根据商品的价格和数量计算总价。

封装:控制对数据的访问

什么是封装?

封装限制对对象属性的直接访问,以防止意外修改。相反,您通过方法与对象的数据进行交互。

示例:使用 getter 和 setter

我们可以通过将属性设置为私有并使用 getter 和 setter 方法控制访问来改进 inventoryitem 类。

class inventoryitem:
    def __init__(self, name, price, quantity):
        self.__name = name  # private attribute
        self.__price = price
        self.__quantity = quantity

    def get_total_price(self):
        return self.__price * self.__quantity

    # getter methods
    def get_name(self):
        return self.__name

    def get_price(self):
        return self.__price

    def get_quantity(self):
        return self.__quantity

    # setter methods
    def set_price(self, new_price):
        if new_price > 0:
            self.__price = new_price

    def set_quantity(self, new_quantity):
        if new_quantity >= 0:
            self.__quantity = new_quantity

# example usage
item = inventoryitem("tablet", 300, 20)
item.set_price(350)  # update price using the setter method
print(f"updated price of {item.get_name()}: ${item.get_price()}")

说明

  • 属性现在是私有的(__name、__price、__quantity)。
  • 您可以使用 getter 和 setter 方法访问或修改这些属性,从而保护对象的内部状态。

继承:在新类中重用代码

什么是继承?

继承允许一个类(子类)从另一个类(父类)继承属性和方法。这促进了代码的可重用性和层次结构建模。

示例:扩展库存系统

让我们扩展我们的系统来处理不同类型的库存物品,例如 perishableitemnonperishableitem

class inventoryitem:
    def __init__(self, name, price, quantity):
        self.__name = name
        self.__price = price
        self.__quantity = quantity

    def get_total_price(self):
        return self.__price * self.__quantity

    def get_name(self):
        return self.__name

class perishableitem(inventoryitem):
    def __init__(self, name, price, quantity, expiration_date):
        super().__init__(name, price, quantity)
        self.__expiration_date = expiration_date

    def get_expiration_date(self):
        return self.__expiration_date

class nonperishableitem(inventoryitem):
    def __init__(self, name, price, quantity):
        super().__init__(name, price, quantity)

# example usage
milk = perishableitem("milk", 2, 30, "2024-09-30")
laptop = nonperishableitem("laptop", 1000, 10)

print(f"{milk.get_name()} expires on {milk.get_expiration_date()}")
print(f"{laptop.get_name()} costs ${laptop.get_total_price()}")

说明

  • perishableitem 和 nonperishableitem 继承自 inventoryitem。
  • super()函数用于调用父类的构造函数(__init__)来初始化公共属性。
  • perishableitem 添加了新属性expiration_date。

多态性:可互换的对象

什么是多态性?

多态性允许不同类的对象被视为公共超类的实例。它使您能够在父类中定义在子类中重写的方法,但您可以在不知道确切的类的情况下调用它们。

示例:多态行为

让我们修改我们的系统,以便我们可以根据项目类型显示不同的信息。

class inventoryitem:
    def __init__(self, name, price, quantity):
        self.__name = name
        self.__price = price
        self.__quantity = quantity

    def display_info(self):
        return f"item: {self.__name}, total price: ${self.get_total_price()}"

    def get_total_price(self):
        return self.__price * self.__quantity

class perishableitem(inventoryitem):
    def __init__(self, name, price, quantity, expiration_date):
        super().__init__(name, price, quantity)
        self.__expiration_date = expiration_date

    def display_info(self):
        return f"perishable item: {self.get_name()}, expires on: {self.__expiration_date}"

class nonperishableitem(inventoryitem):
    def display_info(self):
        return f"non-perishable item: {self.get_name()}, price: ${self.get_total_price()}"

# example usage
items = [
    perishableitem("milk", 2, 30, "2024-09-30"),
    nonperishableitem("laptop", 1000, 10)
]

for item in items:
    print(item.display_info())  # polymorphic method call

说明

  • perishableitem 和 nonperishableitem 中均重写了 display_info() 方法。
  • 当您对对象调用 display_info() 时,python 会根据对象的类型使用适当的方法,即使特定类型在运行时未知。

高级概念:装饰器和类方法

类方法和静态方法

  • 类方法是属于类本身的方法,而不是属于任何对象的方法。它们标有@classmethod。
  • 静态方法不访问或修改类或实例特定的数据。它们被标记为@staticmethod。

示例:使用类方法管理库存

让我们添加一个类级别的方法来跟踪库存中的商品总数。

class inventoryitem:
    total_items = 0  # class attribute to keep track of all items

    def __init__(self, name, price, quantity):
        self.__name = name
        self.__price = price
        self.__quantity = quantity
        inventoryitem.total_items += quantity  # update total items

    @classmethod
    def get_total_items(cls):
        return cls.total_items

# example usage
item1 = inventoryitem("laptop", 1000, 5)
item2 = inventoryitem("smartphone", 500, 10)

print(f"total items in inventory: {inventoryitem.get_total_items()}")

说明

  • total_items 是所有实例共享的类属性。
  • 类方法 get_total_items() 允许我们访问此共享数据。

oop 中的装饰器

oop 中的装饰器通常用于修改方法的行为。例如,我们可以创建一个装饰器来自动记录库存系统中的方法调用。

def log_method_call(func):
    def wrapper(*args, **kwargs):
        print(f"Calling method {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

class InventoryItem:
    def __init__(self, name, price, quantity):
        self.__name = name
        self.__price = price
        self.__quantity = quantity

    @log_method_call
    def get_total_price(self):
        return self.__price * self.__quantity

# Example usage
item = InventoryItem("Tablet", 300, 10)
print(item.get

_total_price())  # Logs the method call

结论

python 中的面向对象编程提供了一种强大而灵活的方式来组织和构建代码。通过使用类、继承、封装和多态性,您可以对复杂系统进行建模并增强代码的可重用性。在这篇文章中,我们介绍了关键的 oop 概念,逐步构建一个库存管理系统来演示每个原则。

python 中的 oop 使您的代码更具可读性、可维护性,并且随着应用程序复杂性的增长而更易于扩展。快乐编码!

以上就是掌握 Python 面向对象编程 (OOP):带有示例的综合指南的详细内容,更多请关注www.sxiaw.com其它相关文章!