0

so I just finished up my first semester of Java and am trying to convert some of our projects into python code. We have a PetRecord class that needs to have a name (str), age (double), and weight (double). The project required creating getters and setters for all of these, as well as a toString.

I found an example __str__ method being used that allows a python object's attributes to be printed to screen just by print(object_name). I'm not sure why my formatting isn't working properly. If someone could enlighten my on why it's throwing:

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'

The code itself (changed the line formatting a bit for this post):

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 

Any help at all would be greatly appreciated.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
user8642594
  • 58
  • 3
  • 9

1 Answers1

0

The reason for the KeyError is that self is not passed to the formatting string.

You though have another problem - single you prepend the instance attribute names with a double underscore (making them "private") - the actual names would be mangled - this means that, for instance, you would need to access __name as self._PetRecord__name:

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

Note that in Python 3.6+, you can make use of the f-strings:

def __str__(self):
    return f"Name: {self._PetRecord__name}\nAge: {self._PetRecord__age}\nWeight: {self._PetRecord__weight}"
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195