使用方法在 python 中创建 class。下面的描述
creating a class in python with a method. description below
我需要有关受在线服装发货订单启发的代码的帮助。它有一个服装 class 和 5 个属性(订单号、购物车中的衣服列表、人名和一个布尔值,说明是否已收到订单。
那我得做一个方法了。此方法应让用户根据以下条件将 Clothing 对象添加到衣服列表中:它必须是 Clothing 项目,不能是随机的。最后一个条件是用户应该能够添加更多,除非购物车中已经有 10 件或更多的服装商品。
我已经制作了服装 class,但我无法连接所有内容并将列表作为属性之一。
class Clothing:
def __init__(self, number, clothes = [], cusname, oreceieved):
self.number= number
self.clothes = clothes
self.cusname = cusname
self.oreceived = False
这就是我目前所拥有的。
注意我有一个要导入的服装文件,所以我已经有数据了。这是我需要帮助的设置。
因此,由于我不知道您的数据文件的具体情况,我将只讨论您可能想要的一般结构。这个答案只会讨论如何实现 add 方法,不会讨论如何对传递给 init 函数的其他参数进行类型检查。
class Clothing:
def __init__(self, number, clothes = [], cusname, oreceieved):
self.number= number
self.clothes = clothes
self.cusname = cusname
self.oreceived = False
self.max_clothes = 10
def add_clothes(self, clothing):
# Start by ensuring that clothing is a clothing item
if not self.is_clothing(clothing):
return
# Check to see if clothes list is 'full'
if len(clothes) >= self.max_clothes:
return
# If valid article of clothing, and list not full, append
self.clothes.append(clothing)
def is_clothing(self, clothing):
'''check that passed clothing is a valid clothing item'''
# Open clothing data file, parse for passed clothing item, return
# True if clothing item found in file, return False otherwise.
我需要有关受在线服装发货订单启发的代码的帮助。它有一个服装 class 和 5 个属性(订单号、购物车中的衣服列表、人名和一个布尔值,说明是否已收到订单。
那我得做一个方法了。此方法应让用户根据以下条件将 Clothing 对象添加到衣服列表中:它必须是 Clothing 项目,不能是随机的。最后一个条件是用户应该能够添加更多,除非购物车中已经有 10 件或更多的服装商品。
我已经制作了服装 class,但我无法连接所有内容并将列表作为属性之一。
class Clothing:
def __init__(self, number, clothes = [], cusname, oreceieved):
self.number= number
self.clothes = clothes
self.cusname = cusname
self.oreceived = False
这就是我目前所拥有的。
注意我有一个要导入的服装文件,所以我已经有数据了。这是我需要帮助的设置。
因此,由于我不知道您的数据文件的具体情况,我将只讨论您可能想要的一般结构。这个答案只会讨论如何实现 add 方法,不会讨论如何对传递给 init 函数的其他参数进行类型检查。
class Clothing:
def __init__(self, number, clothes = [], cusname, oreceieved):
self.number= number
self.clothes = clothes
self.cusname = cusname
self.oreceived = False
self.max_clothes = 10
def add_clothes(self, clothing):
# Start by ensuring that clothing is a clothing item
if not self.is_clothing(clothing):
return
# Check to see if clothes list is 'full'
if len(clothes) >= self.max_clothes:
return
# If valid article of clothing, and list not full, append
self.clothes.append(clothing)
def is_clothing(self, clothing):
'''check that passed clothing is a valid clothing item'''
# Open clothing data file, parse for passed clothing item, return
# True if clothing item found in file, return False otherwise.