【发布时间】:2020-11-22 20:40:00
【问题描述】:
有人能以初学者友好的方式告诉我为什么我不能打印分子名称(在本例中为“NaCl”)吗?
如果我用return Molecule([self.label, other.label]) 替换return Molecule([self, other]) 我的代码可以工作并产生预期的输出,但我想传递实例而不是属性。这是我的代码:
class Atom:
def __init__(self, label):
self.label = label
def __add__(self, other):
return Molecule([self, other])
class Molecule:
def __init__(self, atoms):
if type(atoms) is list:
self.atoms = atoms
def __repr__(self):
lol = ''
for i in self.atoms:
lol += i
return lol
sodium = Atom("Na")
chlorine = Atom("Cl")
salt = Molecule([sodium, chlorine])
salt = sodium + chlorine
print(salt)
这是练习图片: my problem
【问题讨论】:
-
请在问题中包含回溯。请参阅minimal reproducible example 以供参考
-
顺便说一句,最好使用
str.join()而不是添加字符串。它还会使Molecule.__repr__更简单——只需return ''.join(self.atoms)。顺便说一句,欢迎来到 SO!