将一个类作为参数传递给python中

时间:2018-03-02 06:30:31

标签: python python-3.x class oop

我是python的新手,我有一个项目要求建立一个购物车。它有一个特殊的要求,我应该去。我坚持使用make add方法并删除。 如何使用类作为方法的参数?为什么?

以下是我的ItemToPurchase的样子

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))

我坚持购物车方法,这是要求 参数化构造函数,它将客户名称和日期作为参数

  • 属性
    • customer_name(string)
    • current_date(string)
    • cart_items(列表)
  • 方法
    • add_item() - 将项目添加到cart_items列表。有参数ItemToPurchase。不归 任何东西。
    • remove_item() - 从cart_items列表中删除项目。有一个字符串(项目的名称)参数。才不是 什么都归还。
    • 如果找不到项目名称,请输出以下消息:购物车中找不到商品。 没有删除。使用例外

2 个答案:

答案 0 :(得分:0)

您不添加class作为参数。 class是数据上的形状定义的操作

在购物车中,您可以提供ItemToPurchase的“实例” - 填充数据的具体对象 - 而不是“形状”。

import datetime as dt        # for the date when creating a cart with name/date

# create an instance of a ShoppingCart with name and date
cart = ShoppingCart("Fred",dt.datetime.now()) 

# create an instance of a ItemToPurchase
item = ItemToPurchase("gum", 2.5, 10, "best tasting chewing gum **ever**")

# and put it into the ShopphingCart instance by using its method add_item()
cart.add_item(item)

# or create the ItemToPurchase-instance on-the-fly, without naming it explicitly

cart.add_item( ItemToPurchase("bubb", 0.5, 3, "best tasting bubble gum **never**") )

# add_item() adds to Carts self.interalItemList
# remove_item() removes from Carts self.interalItemList - eventually only
#     subtracting from an item (10 shoes in, remove 8 shoes, 2 left) etc.

示例用法和类的示例:

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

答案 1 :(得分:-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)