|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
# 作者:小甲鱼
# 来源:https://fishc.com.cn/thread-213592-1-1.html
# 本代码著作权归作者所有,禁止商业或非商业转载,仅供个人学习使用,违者必究!
# Copyright (c) fishc.com.cn All rights reserved
class Meet:
nums = 0
class Egg(Meet):
name = "鸡蛋"
price = 1
class Beef(Meet):
name = "牛肉"
price = 25
class Mutoon(Meet):
name = "羊肉"
price = 30
class Vegetable:
nums = 0
class Onion(Vegetable):
name = "洋葱"
price = 2
class Tomato(Vegetable):
name = "番茄"
price = 2
class Potato(Vegetable):
name = "土豆"
price = 3
class Radish(Vegetable):
name = "萝卜"
price = 3
class Menu:
def order(self):
self.x = []
print("客官想要吃点什么?")
dishes = input("1.洋葱炒牛肉;2.洋葱炒羊肉;3.煎蛋;4.番茄炒蛋;5.土豆萝卜炖羊肉:")
dishes = dishes.split()
while dishes:
dish = dishes.pop(0)
if dish == '1':
onion = Onion()
onion.num = 1
beef = Beef()
beef.num = 1
self.x.extend([beef, onion])
if dish == '2':
onion = Onion()
onion.num = 1
mutoon = Mutoon()
mutoon.num = 1
self.x.extend([mutoon, onion])
if dish == '3':
egg = Egg()
egg.num = 2
self.x.append(egg)
if dish == '4':
tomato = Tomato()
tomato.num = 2
egg = Egg()
egg.num = 3
self.x.extend([tomato, egg])
if dish == '5':
potato = Potato()
potato.num = 2
radish = Radish()
radish.num = 1
mutoon = Mutoon()
mutoon.num = 2
self.x.extend([potato, radish, mutoon])
print(self.x)
def pay(self):
total = 0
for each in self.x:
print(each.name, each.price, "*", each.num)
total += each.price * each.num
print(f"感谢惠顾,您一共消费了 {total} 元,欢迎下次光临~")
以上是一个用于点菜的代码,有两个菜都需要调用Egg,并且对属性num有不同的赋值 然而却选择了相同的对象名,表达式都为egg = Egg()。这样多次实例化一个类用的都是同一个对象名是可以的吗? 求解答
问题解答:
在这段代码中,多次实例化一个类并使用相同的对象名是可以的,因为每次实例化都会创建一个新的对象,并将其赋值给对象名。虽然使用相同的对象名,但是它们指向的是不同的内存空间,所以不会互相干扰。
在这个例子中,使用相同的对象名 egg是合法的,因为每次实例化 Egg类都会创建一个新的 egg对象。这些对象具有不同的属性和方法,尽管对象名相同,但它们在内存中是不同的实例。
如果你想让每个菜品都创建一个独立的对象,可以修改代码如下:
- class Menu:
- def order(self):
- self.x = []
- print("客官想要吃点什么?")
- dishes = input("1.洋葱炒牛肉;2.洋葱炒羊肉;3.煎蛋;4.番茄炒蛋;5.土豆萝卜炖羊肉:")
- dishes = dishes.split()
- while dishes:
- dish = dishes.pop(0)
- if dish == '1':
- onion = Onion()
- onion.num = 1
- beef = Beef()
- beef.num = 1
- self.x.extend([beef, onion])
- if dish == '2':
- onion = Onion()
- onion.num = 1
- mutoon = Mutoon()
- mutoon.num = 1
- self.x.extend([mutoon, onion])
- if dish == '3':
- egg1 = Egg()
- egg1.num = 2
- self.x.append(egg1)
- if dish == '4':
- tomato = Tomato()
- tomato.num = 2
- egg2 = Egg()
- egg2.num = 3
- self.x.extend([tomato, egg2])
- if dish == '5':
- potato = Potato()
- potato.num = 2
- radish = Radish()
- radish.num = 1
- mutoon = Mutoon()
- mutoon.num = 2
- self.x.extend([potato, radish, mutoon])
- print(self.x)
- def pay(self):
- total = 0
- for each in self.x:
- print(each.name, each.price, "*", each.num)
- total += each.price * each.num
- print(f"感谢惠顾,您一共消费了 {total} 元,欢迎下次光临~")
复制代码
以上修改后的代码中,每个菜品都创建了一个独立的对象,对象名也相应地进行了修改,以确保每个对象都是唯一的。这样做可以保证每个对象都有自己独立的属性和方法。
如果回答对你有帮助,请给我一个最佳答案! 
|
|