创建类方法\uu str__

2024-09-30 10:38:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个需要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()

Tags: ofthe代码nameselfagereturnis
1条回答
网友
1楼 · 发布于 2024-09-30 10:38:33

在main函数(pet.py)的代码中,调用print时没有任何参数。您需要使用您的宠物实例调用print作为参数:

pets = classPet.Pet(name, animal_type, age)
print(pets)  # see here

您还需要修复__str__方法中的错误: __str__方法不会像print()函数那样将其所有参数连接到字符串。相反,它必须返回单个字符串

__str__方法中,用逗号分隔字符串的不同部分。这将使python认为它正在处理一个元组。我建议使用pythonsformat函数实现以下解决方案:

def __str__(self):
    return "Pet Name: {}\nAnimal Type: {}\nAge: {}".format(self.__name, self.__animal_type, self.__age)

字符串中的{}部分是占位符,通过format函数用括号中的参数替换占位符。它们按顺序被替换,因此第一个被self.__name等替换

相关问题 更多 >

    热门问题