Reputation:
I'm having trouble printing a method with a variable.
If I do print (pet.__str__())
, it works as expected. However I'm trying to loop through the method using variables to replace "pet" with a variable. I'm then assigning it to a variable and trying to print it. When I print it, it literally prints the string pet.__str__()
instead of calling the method. I'm not sure what I'm doing wrong. Here's a general overview of my code. Thanks
pet = Pet('Taz')
my_list = ["pet", "dog", "big_dog", "small_dog"]
my_string = ["animal_variable.__str__()", "animal_variable.kind", "animal_variable.color", "animal_variable.do_tricks()"]
sentence1 = []
sentence1 = my_string[0]
print (sentence1) #DEBUGGING*****************************************
print (sentence1.replace('animal_variable', my_list[0]))
print (type(sentence1))
*** HERE'S THE OUTPUT I GET *******
animal_variable.__str__()
pet.__str__(),
class 'str'
*** If I do this it works as expected, however this doesn't allow me to loop through different variables in my list
print (pet.__str__())
Upvotes: 0
Views: 88
Reputation: 43206
Try this method:
my_list = ["pet", "dog", "big_dog", "small_dog"]
for pet in map(Pet, my_list):
print ("{}, Kind: {}, Color: {}\nTricks: {}".format(str(pet), pet.kind, pet.color, pet.do_tricks()))
If you already have a list of animals, then simply replace the for loop above with:
for pet in my_list:
Another method to use is to override __str__
method of the class, to return the above. Something like:
def __str__(self):
return "Kind: {}, Color: {}\nTricks: {}".format(self.kind, self.color, self.do_tricks())
Upvotes: 1