【问题标题】:Python TypeError: must be str, not AtomPython TypeError:必须是 str,而不是 Atom
【发布时间】: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!

标签: python oop repr


【解决方案1】:

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

lol += i

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

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

所以你有两个选择。

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

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

【讨论】:

    【解决方案2】:

    在您的 Atom 类上也实现__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)
    

    【讨论】:

    • 感谢您的建议。它让我对“ repr ”方法有了更多的了解
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    相关资源
    最近更新 更多