簡體   English   中英

格式化python3類中__str__的輸出字符串

[英]Formatting output string for __str__ in python3 class

所以我剛結束Java的第一學期,並試圖將我們的一些項目轉換為python代碼。 我們有一個PetRecord類,需要有一個名稱(str),年齡(double)和體重(double)。 該項目需要為所有這些創建getter和setter以及toString。

我發現正在使用一個示例__str__方法,該方法允許僅通過print(object_name)將python對象的屬性打印到屏幕上。 我不確定為什么我的格式無法正常工作。 如果有人可以啟發我理解為什么會拋出該異常:

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 

任何幫助將不勝感激。

KeyError的原因是self不傳遞給格式化字符串

但是,您還有另一個問題-在實例屬性名稱前加雙下划線(使它們成為“私有”)- 實際名稱將被修飾 -這意味着,例如,您將需要以__name身份訪問self._PetRecord__name

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM