Python: 练习 魔术函数__add__(self,other)Python: 练习 魔术函数__add__(self,other)Python: 练习 魔术函数__add__(self,other)Python: 练习 魔术函数__add__(self,other)
  • 首页
  • 博客
  • 文件
  • 书签
  • 分析
  • 登录
Search
Generic filters

Python: 练习 魔术函数__add__(self,other)

Published by admin at 2022年3月3日
Categories
  • Practice
Tags
class CellPhone:  # 定义一个手机类的模板,包括品牌(brand)和价格(price)
    def __init__(self, brand, price=0.0):
        self.brand = brand
        self.price = price

    def __str__(self):
        return str(self.price)

    def __add__(self, other):  # 魔术函数,self 指实例化对象本身,other 指另一个实例化对象本身.
        return CellPhone(brand='', price=(self.price + other.price))  # 将实例化对象的价格求和,得到两个品牌手机价格的和.


c1 = CellPhone('iPhone 7', 7000.0)  # 实例化对象1
c2 = CellPhone('MI note 2', 2000.0)  # 实例化对象2
c3 = CellPhone('Nokia', 1000.0)  # 实例化对象3

print(c1 + c2 + c3)

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Categories

  • 猫
  • Python
  • MySQL
  • Django
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • php
  • Practice
  • Virtualization
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • Router
  • Office
  • WordPress
  • SEO
  • English
  • Games
  • Recipes
  • living
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2022 Alaica Blog support@alaica.com