所以我试图使用嵌套的while循环生成类对象的列表。我有两种类型的类,normal_class和special_class。
对于special_class,我通过执行special_class.set(x,y)给它x,y坐标。对于普通班,我只是保持原样。
如果我通过执行special_class.set(x,y)附加另一个special_class,然后ls.append(special_class)会覆盖第一个的坐标,所以我最终得到两个具有相同坐标的special_class,而不是两个带有单独的坐标。
我最近才开始使用Python进行编程,所以任何帮助都将是有用的:)
这是一些伪代码:
代码!
class special_class:
def __init__(self):
self.char = "X"
def set_pos(self, x, y):
self.x = x
self.y = y
def get_pos(self):
return (self.x, self.y)
class normal_class:
def __init__(self):
self.char = "Y"
class also_special_class:
def __init__(self):
self.char = "Z"
def set_pos(self, x, y):
self.x = x
self.y = y
def get_pos(self):
return (self.x, self.y)
string = "XYXZ"
dict = {"X": special_class(), "Y": normal_class(), "Z": also_special_class()}
ls = []
i = 0
while i < len(string):
k = 0
keys = list(dict.keys())
while k < len(keys):
if string[i] == keys[k]:
instance = dict[keys[k]]
if keys[k] == "X" or keys[k] =="Z": # i and k numbers that change
special_class = instance.set_pos(i, k) # why is special_class None?
### this code is ugly but it's the only way I know of doing it without errors
### however, the position of the two elements is not what I put into it initially
special_instance = dict[keys[k]]
special_instance.set_pos(i,k)
print(special_instance.get_pos())
instance = special_instance
ls.append(instance)
k += 1
i += 1
print()
print(ls)
print("\nPosition after finished loop")
print(ls[0].get_pos())
print(ls[2].get_pos())
如果您能给我有关a)为什么注释的special_class片段返回Noneb)提供有关改进我的代码的指针,特别是这部分]
special_instance = dict[keys[k]] special_instance.set_pos(i,k) print(special_instance.get_pos()) instance = special_instance
c)解释为什么我要为get_pos获得相同的值,以及如何修复我的代码以使其按预期工作,这真是太神奇了!
所以我试图使用嵌套的while循环生成类对象的列表。我有两种类型的类,normal_class和special_class。对于special_class,我通过执行...
您需要使用copy.deepcopy()
来制作类对象的非浅表副本。这将添加类对象(copy.deepcopy()
),而不是对其的引用。