在python3类中格式化__str__的输出字符串

时间:2017-12-16 20:39:53

标签: python python-3.x formatting

所以我刚完成了我的第一个Java学期,并试图将我们的一些项目转换为python代码。我们有一个PetRecord类需要有一个名字(str),年龄(双倍)和权重(double)。该项目需要为所有这些创建getter和setter,以及toString。

我找到了一个示例__str__方法,它允许python对象的属性仅通过print(object_name)打印到屏幕上。我不确定为什么我的格式化不正常。如果有人可以告诉我为什么要扔它:

Traceback (most recent call last):
  File "PetRecord.py", line 92, in <module>
    print(TestPet)
  File "PetRecord.py", line 49, in __str__
    return('Name: {self.__name} \nAge: {self.__age} \nWeight:{self.__weight}').format(**self.__dict__) # this is printing literally 
KeyError: 'self'

代码本身(更改了此帖子的行格式化):

class PetRecord(object):
  '''
  All pets come with names, age and weight
  '''
  def __init__(self, name='No Name', age=-1.0,
               weight=-1.0):
    # data fields
    self.__name = name
    self.__age = age
    self.__weight = weight

  def __str__(self):
    # toString()  
    return('Name: {self.__name} \nAge: {self.__age} 
          \nWeight:{self.__weight}').format(
          **self.__dict__) # this is printing literally 

任何帮助都将非常感谢。

1 个答案:

答案 0 :(得分:0)

KeyError的原因是 self未传递给格式化字符串

你有另外一个问题 - 单个你在实例属性名称前加上双下划线(使它们成为“私有”) - the actual names would be mangled - 这意味着,例如,你需要访问{{1} } __name

self._PetRecord__name

请注意,在Python 3.6+中,您可以使用f-strings

def __str__(self):
    return "Name: {self._PetRecord__name}\nAge: {self._PetRecord__age}\nWeight: {self._PetRecord__weight}".format(self=self)