0

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__())
6
  • pet is already variable - what other variable do you what to use ? Commented Feb 5, 2017 at 20:39
  • 1
    BTW: instead of pet.__str__() you should use str(pet) - it is prefered method. Commented Feb 5, 2017 at 20:40
  • Are you trying to eval a string to get your variables? Commented Feb 5, 2017 at 20:42
  • "pet.__str__()" is only string so don't expect that it will call a method. Commented Feb 5, 2017 at 20:42
  • 5
    Don't vandalize your posts. Commented Feb 5, 2017 at 21:13

1 Answer 1

1

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())
Sign up to request clarification or add additional context in comments.

2 Comments

While this general idea seems to be better than the OPs, I think you misunderstood something. It looks to me like pet as a string is meant to refer to the pet variable (maybe with eval?). It looks, then, like all the strings in my_list are variable names. Therefore, I think the loop should start with for animal in [pet, dog, ...]
@zondo Hmm...possibly. I will add that as another option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.