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.