我正在编写一个需要str方法的程序。但是,当我运行代码时,它只输出:
What is the name of the pet: Tim
What type of pet is it: Turtle
How old is your pet: 6
如何从str方法打印出我需要的内容? 这是我的东西。 这是我的类的代码(classPet.py)
class Pet:
def __init__(self, name, animal_type, age):
self.__name = name
self.__animal_type = animal_type
self.__age = age
def set_name(self, name):
self.__name = name
def set_type(self, animal_type):
self.__animal_type = animal_type
def set_age(self, age):
self.__age = age
def get_name(self):
return self.__name
def get_animal_type(self):
return self.__animal_type
def get_age(self):
return self.__age
def __str__(self):
return 'Pet Name:', self.__name +\
'\nAnimal Type:', self.__animal_type +\
'\nAge:', self.__age
这是我的主函数(pet.py)的代码:
import classPet
def main():
# Prompt user to enter name, type, and age of pet
name = input('What is the name of the pet: ')
animal_type = input('What type of pet is it: ')
age = int(input('How old is your pet: '))
pets = classPet.Pet(name, animal_type, age)
print()
main()
在main函数(pet.py)的代码中,调用print时没有任何参数。您需要使用您的宠物实例调用print作为参数:
您还需要修复
__str__
方法中的错误:__str__
方法不会像print()
函数那样将其所有参数连接到字符串。相反,它必须返回单个字符串在
__str__
方法中,用逗号分隔字符串的不同部分。这将使python认为它正在处理一个元组。我建议使用pythonsformat
函数实现以下解决方案:字符串中的
{}
部分是占位符,通过format
函数用括号中的参数替换占位符。它们按顺序被替换,因此第一个被self.__name
等替换相关问题 更多 >
编程相关推荐