首页 > 分享 > Python类中方法种类与修饰符从基础到实战详解

Python类中方法种类与修饰符从基础到实战详解

from abc import ABC, abstractmethod

from datetime import datetime

class Product(ABC):

    tax_rate = 0.1 

    def __init__(self, name, price, quantity):

        self.name = name

        self.price = price

        self.quantity = quantity

        self.__id = self.__generate_id() 

    def __generate_id(self):

        timestamp = int(datetime.now().timestamp())

        return f"PROD-{timestamp}"

    @property

    def id(self):

        return self.__id

    @abstractmethod

    def display_info(self):

        pass

    @classmethod

    def update_tax_rate(cls, new_rate):

        cls.tax_rate = new_rate

    @staticmethod

    def calculate_discount(price, discount):

        return price * (1 - discount)

    def sell(self, quantity):

        if quantity <= self.quantity:

            self.quantity -= quantity

            total = quantity * self.price * (1 + self.tax_rate)

            return f"已售出 {quantity} 件 {self.name}, 总价: {total:.2f}"

        return "库存不足"

class Book(Product):

    def __init__(self, name, price, quantity, author):

        super().__init__(name, price, quantity)

        self.author = author

    def display_info(self):

        return (f"图书: {self.name}n"

                f"作者: {self.author}n"

                f"价格: ¥{self.price:.2f}n"

                f"库存: {self.quantity}件n"

                f"含税价: ¥{self.price * (1 + self.tax_rate):.2f}")

class Electronics(Product):

    def __init__(self, name, price, quantity, warranty):

        super().__init__(name, price, quantity)

        self.warranty = warranty 

    def display_info(self):

        return (f"电子产品: {self.name}n"

                f"保修: {self.warranty}个月n"

                f"价格: ¥{self.price:.2f}n"

                f"库存: {self.quantity}件n"

                f"含税价: ¥{self.price * (1 + self.tax_rate):.2f}")

if __name__ == "__main__":

    Product.update_tax_rate(0.15)

    book = Book("Python编程", 59.99, 100, "John Doe")

    phone = Electronics("智能手机", 2999.99, 50, 24)

    print(book.display_info())

    print("n" + phone.display_info())

    print("n" + book.sell(2))

    print(phone.sell(1))

    discounted_price = Product.calculate_discount(phone.price, 0.2)

    print(f"n手机8折价: ¥{discounted_price:.2f}")

    print(f"n图书ID: {book.id}")

相关知识

Python类中方法种类与修饰符从基础到实战详解
Python从小白到大牛:项目实战3:开发PetStore宠物商店项目
Web3.0宠物商店实战教程:ETH智能合约入门到实践
如何训练宠物狗成为优秀的猎犬?(从基础训练到实战操作,详解打造顶级猎犬的方法和技巧)
14天Java基础学习——第6天:面向对象编程(类与对象)
使用Python实现高效喂狗算法:从入门到进阶的编程技巧详解
python定义一个动物类animal
Python面向对象与模块化:构建宠物管理系统的实战案例
python 类的超基础应用宠物小狗
摄影构图与用光从入门到精通(知名摄影家联袂推荐,摄影实战+视频教学=快速提升摄影构图与用光技术)

网址: Python类中方法种类与修饰符从基础到实战详解 https://m.mcbbbk.com/newsview1214927.html

所属分类:萌宠日常
上一篇: 宠物龟的常见品种介绍
下一篇: 杂交龟:龟类品种改良新方向