唼喋菁藻
后端开发
·09-21 17:46
Day 15 🧭行动:学习实例方法与魔法方法 🤓体会:Python中提供的__xxx__形式的特殊方法 魔法方法无需手动调用,Python会在合适的时机自动调用 🧑‍💻代码: # class Car: # # def __init__(self, c_color, c_brand, c_name, c_price): # self.color = c_color # self.brand = c_brand # self.name = c_name # self.price = c_price # print("Car类型对象初始化完毕,对象属性添加完毕!") # # def running(self): # print(f"{self.brand} {self.name}正在行驶中~~~") # # def cost(self,discount,rate=0.1): # """ # 计算花费的总金额,由车的价格和税费组成 # :param discount: # :param rate: # :return: # """ # cost = self.price * discount + rate * self.price # return cost # #示例 # c1 = Car("red","BMW","X8",80000) # #调用对象中的方法 # c1.running() # total1 = c1.cost(0.5,0.1) # print("总费用为",total1) # total2 = c1.cost(0.5) # print("总费用为",total2) class Car: def __init__(self, c_color, c_brand, c_name, c_price): self.color = c_color self.brand = c_brand self.name = c_name self.price = c_price print("Car类型对象初始化完毕,对象属性添加完毕!") def running(self): print(f"{self.brand} {self.name}正在行驶中~~~") def cost(self,discount,rate=0.1): cost = self.price * discount + rate * self.price return cost #魔法方法 def __str__(self): return f"{self.color} {self.brand} {self.name} {self.price}" def __eq__(self,other): return self.color == other.color and self.brand == other.brand and self.name == other.name and self.price == other.price def __lt__(self, other): return self.price < other.price #测试 c1 = Car("白色","BYD","han",15000) print(c1) c2 = Car("白色","BYD","han",15000) print(c2) print(c1 == c2) print(c1 < c2)
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP