【发布时间】:2023-03-15 06:44:02
【问题描述】:
我正在尝试用这种结构实现一个类:
class type_of_thing():
def __init__(self, type, code, version, description, year, family):
self.type = type
self.code = code
self.version = version
self.description = description
self.year = year
self.family = family
# with this I would create a new element of this class:
obj_type1 = type_of_thing(type = "x", code = "WRT-001", version= "1-10", description= "custom", year = "2016", family = "class1")
obj_type1_2 = type_of_thing(type = "x", code = "WRT-001", version= "1-11", description= "custom", year = "2016", family = "class1")
obj_type2 = type_of_thing(type = "xy", code = "WRT-001", version= "1-12", description= "custom", year = "2016", family = "class1")
但我必须创建数百个这样的元素,我已经将它们放在这样的列表中:
type of thing1:
type = "x",
code = "WRT-001",
version= "1-10",
description= "custom",
year = "2016",
family = "class1"
type = "x",
code = "WRT-001",
version= "1-11",
description= "custom",
year = "2016",
family = "class1"
type of thing2:
type = "xy",
code = "WRT-001",
version= "1-12",
description= "custom",
year = "2016",
family = "class1"
type = "xy",
code = "WRT-001",
version= "1-10",
description= "custom",
year = "2016",
family = "class1"
type of thing3:
...
...
...
假设我可以将它们放在这样的列表中:
type_of_thing1 = ["x","WRT-001","1-10","custom","2016","class1"]
type_of_thing1_2 = ["x","WRT-001","1-11","custom","2016","class1"]
type_of_thing2 = ["xy","WRT-001","1-12","custom","2016","class1"]
type_of_thing3 = ["...","...","...","...","..","..."]
所以我试图找到一种使用类来实现这一点的pythonic方法,并避免创建一堆对象或一堆列表来存储我拥有的所有事物类型的组合。
像列表一样管理它并按位置访问其元素而不是创建一个类会更好吗? 你认为我可以做些什么来改进我的代码?
【问题讨论】:
-
请edit您的问题,并至少包含您已经拥有的列表的部分内容,因为这将是提供具体答案所必需的。
-
更好地使用列表或字典 - 它有助于使用它。
-
@furas 我正在考虑使用一个类,因为如果将来我需要添加一个新元素,我只需要调用类对象并放置所需的参数。
-
对不起,我正在考虑将对象保留在列表
obj_type.append( type_of_thing(...) )上。在创建对象type_of_thing = [ ["x", ...], ["x", ...], ]之前与数据相同,然后您可以使用for循环创建包含对象的列表。
标签: python class implementation