将类作为参数传递给python中其他类中的方法
我是python新手,我有一个项目要求构建一个购物车。它有一个具体的要求,我应该去。我一直坚持使用makeadd方法和remove方法。 如何使用类作为方法的参数,为什么 下面是我的ItemToPurchase的样子将类作为参数传递给python中其他类中的方法,python,python-3.x,class,oop,Python,Python 3.x,Class,Oop,我是python新手,我有一个项目要求构建一个购物车。它有一个具体的要求,我应该去。我一直坚持使用makeadd方法和remove方法。 如何使用类作为方法的参数,为什么 下面是我的ItemToPurchase的样子 class ItemToPurchase: def __init__(self, item_name, item_price, item_quantity, item_description): self.item_name = item_name
class ItemToPurchase:
def __init__(self, item_name, item_price, item_quantity, item_description):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = int(item_quantity)
self.item_description = item_description
def print_item_cost(self):
if self.item_price <=0:
raise ValueError('Invaild price')
price_for_quntatity = self.item_price * self.item_quantity
print('%s %d @ %d = %d'%(self.item_name, self.item_quantity, self.item_price, price_for_quntatity ))
def __str__(self):
return ('%s'%(self.item_description))
class ItemToPurchase:
定义初始(自身、项目名称、项目价格、项目数量、项目描述):
self.item\u name=item\u name
self.item\u price=item\u price
self.item\u quantity=int(item\u quantity)
self.item\u description=item\u description
def打印项目成本(自身):
如果self.item_price您不添加类
作为参数。类是数据的形状和定义的动作
你给你的购物车提供了ItemToPurchase
的“实例”-充满数据的具体对象-而不是“形状”
实例用法和类的示例:
class Fruit:
"""POCO for a fruit with a name and size"""
def __init__(self, name, size):
self.name = name
self.size = size
# TODO: needs some more __xxxx__ implemented
class FruitBasket:
"""Basket for fruits, has a finite size."""
def __init__(self,size= 10):
self.size = size
self.fruitsInIt = []
def addFruit(self, fruit:Fruit):
"""Add a fruit if size fits, prints output for added/not added."""
currSize = sum( x.size for x in self.fruitsInIt)
if currSize+fruit.size > self.size:
print("Can not fit {} size {} in, its too big. Remaining space: {}"
.format(fruit.name, fruit.size, self.size-currSize))
else:
print("Putting {} in. Remaining space: {}".format(fruit.name, self.size-currSize-fruit.size))
self.fruitsInIt.append(fruit)
def view(self):
"""Print all fruits with sizes"""
for f in self.fruitsInIt:
print(f.name, f.size)
def eatAll(self,fruitName:str):
"""If present, eat all fruits of given name, else print message"""
if not fruitName in [x.name for x in self.fruitsInIt]:
print("No {} left :((".format(fruitName))
return
for f in self.fruitsInIt:
if f.name == fruitName:
print("Eating {} of size {}.".format(f.name, f.size))
else:
print("Do not like {}.".format(f.name))
self.fruitsInIt = [x for x in self.fruitsInIt if x.name != fruitName]
import random # for random data
fruits = ["Apple", "Orange", "Melon", "Banana"]
b = FruitBasket(12) # instance of basket with size 12
for _ in range(10): # try to add 10 random fruits
b.addFruit(Fruit(random.choice(fruits), random.randint(1,3)))
b.view() # show basket
b.eatAll("Apple") # eat all apples (if any in)
b.view() # show basket again
输出:
# adding things to basket
Putting Banana in. Remaining space: 10
Putting Melon in. Remaining space: 9
Putting Banana in. Remaining space: 6
Putting Orange in. Remaining space: 5
Putting Melon in. Remaining space: 2
Can not fit Melon size 3 in, its too big. Remaining space: 2
Putting Melon in. Remaining space: 1
Can not fit Melon size 3 in, its too big. Remaining space: 1
Can not fit Melon size 3 in, its too big. Remaining space: 1
Can not fit Apple size 3 in, its too big. Remaining space: 1
# viewing basket
Banana 2
Melon 1
Banana 3
Orange 1
Melon 3
Melon 1
# eatAll apples
No Apple left :((
# view basket again
Banana 2
Melon 1
Banana 3
Orange 1
Melon 3
Melon 1
检查此项可能满足您的需求:-
import datetime
class Customer_name:
def __init__(self,name):
self.cust_name = name
self.time = str(datetime.datetime.now())
self.item_list = []
def add_item(self,item_name, item_price, item_quantity, item_description):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = int(item_quantity)
self.item_description = item_description
self.item_list.append(([self.item_name,self.item_price,self.item_quantity,self.item_description]))
def remove_item(self,check_item):
for item in self.item_list:
if check_item in item:
self.item_list.remove(item)
return
@property
def cart_items(self):
return self.item_list
@property
def print_item_cost(self):
if self.item_price <=0:
raise ValueError('Invaild price')
price_for_quntatity = self.item_price * self.item_quantity
return ('Cust Name:{} {} {}@{}= {} date {}'.format(self.cust_name,self.item_name, self.item_quantity, self.item_price,price_for_quntatity,self.time ))
a = Customer_name("John")
a.add_item('apple',20,10,"good for health")
a.add_item("Mango",50,30,"tasty")
a.add_item("Guava",50,30,"tasty")
a.add_item("Orange",50,30,"tasty")
a.remove_item("Mango")
print(a.cart_items)
print(a.print_item_cost)
导入日期时间
类别客户名称:
定义初始化(self,name):
self.cust_name=名称
self.time=str(datetime.datetime.now())
self.item_list=[]
def添加项目(自身、项目名称、项目价格、项目数量、项目说明):
self.item\u name=item\u name
self.item\u price=item\u price
self.item\u quantity=int(item\u quantity)
self.item\u description=item\u description
self.item\u list.append([self.item\u name,self.item\u price,self.item\u quantity,self.item\u description]))
def移除项目(自身、检查项目):
对于self.item_列表中的项目:
如果选中项目中的项目:
self.item_list.remove(项目)
回来
@财产
def cart_项目(自身):
返回self.item\u列表
@财产
def打印项目成本(自身):
如果self.item_price,但据说是ShoppingCart类中的add_item()方法将以ItemToBurchase作为参数,ItemToBurchase是一个类。加上所有这些类都在同一个文件中,所以我不需要import@MariamAdel您不需要导入datetime
模块吗?Python不是强类型的。您可以创建添加项目(self,blablubb):
toShoppingCart-
blablubb`就是给定参数在该函数中使用时的名称。然后在调用它时将一个具体的ItemToPurchase对象放入其中…为什么您的类命名为customer\u name
-类开始使用capital,而它是一个购物车
。为什么您的customer\u name
属性属于一个itemtopourchase
?你为什么根本不使用itemtopourchase
?
import datetime
class Customer_name:
def __init__(self,name):
self.cust_name = name
self.time = str(datetime.datetime.now())
self.item_list = []
def add_item(self,item_name, item_price, item_quantity, item_description):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = int(item_quantity)
self.item_description = item_description
self.item_list.append(([self.item_name,self.item_price,self.item_quantity,self.item_description]))
def remove_item(self,check_item):
for item in self.item_list:
if check_item in item:
self.item_list.remove(item)
return
@property
def cart_items(self):
return self.item_list
@property
def print_item_cost(self):
if self.item_price <=0:
raise ValueError('Invaild price')
price_for_quntatity = self.item_price * self.item_quantity
return ('Cust Name:{} {} {}@{}= {} date {}'.format(self.cust_name,self.item_name, self.item_quantity, self.item_price,price_for_quntatity,self.time ))
a = Customer_name("John")
a.add_item('apple',20,10,"good for health")
a.add_item("Mango",50,30,"tasty")
a.add_item("Guava",50,30,"tasty")
a.add_item("Orange",50,30,"tasty")
a.remove_item("Mango")
print(a.cart_items)
print(a.print_item_cost)