Python TypeError: must be str, not Atom

Python TypeError: must be str, not Atom

有人可以用初学者友好的方式告诉我为什么我不能打印分子名称(在这种情况下 '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

也在您的 Atom class 上实现 __repr__ 函数,并使用 str(atom);

调用它
class Atom:
    def __init__(self, label):
        self.label = label

    def __add__(self, other):
        return Molecule([self, other])

    def __repr__(self):
        return self.label

class Molecule:
    def __init__(self, atoms):
        if type(atoms) is list:
            self.atoms = atoms

    def __repr__(self):
        lol = ''
        for i in self.atoms:
            lol += str(i)
        return lol

sodium = Atom("Na")
chlorine = Atom("Cl")
salt = Molecule([sodium, chlorine])
salt = sodium + chlorine
print(salt)

您的踪迹告诉您需要查看哪条线。 第 14 行你有这个

lol += i

Python 正在努力解决这个问题,因为首先 lol 是一个字符串。我们知道这是因为您用 lol = ''

分配了它

但现在您要求 Python 将 Atom 的实例附加到 str。但是你还没有告诉 Python 它应该如何将 Atom 的类型附加到 str.

所以你有两个选择。

  1. 在您的 Atom class 中,覆盖 __repr__ 函数,然后将 i 转换为字符串。

  2. 在您的 Molecule class 中,用 i.label 附加到 lol 而不仅仅是 i