简体   繁体   English

创建类方法 __str__

[英]Creating a class method __str__

I am working on a program that needs a str method.我正在开发一个需要str方法的程序。 However, when I run the code, it only outputs:但是,当我运行代码时,它只输出:

What is the name of the pet: Tim
What type of pet is it: Turtle
How old is your pet: 6

How can I print out what I need from the str method?如何从 str 方法打印出我需要的内容? Here is what I have.这是我所拥有的。 This is the code for my class (classPet.py)这是我班级的代码(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

This is the code for my main function (pet.py):这是我的主函数(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()

In the code for your main function (pet.py), you are calling print without any parameters.在您的主函数 (pet.py) 的代码中,您调用了不带任何参数的 print。 You need to call print with your pet instance as a parameter:您需要使用您的宠物实例作为参数调用 print :

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

You also need to fix an error in your __str__ method: the __str__ method doesn't concatenate all of its arguments to a string like the print() function does it.您还需要修复__str__方法中的错误: __str__方法不会像print()函数那样将其所有参数连接到字符串。 Instead, it must return a single string.相反,它必须返回单个字符串。

In your __str__ method you are seperating your different parts of the string by commas.在您的__str__方法中,您用逗号分隔字符串的不同部分。 This will make python think that it's dealing with a tuple.这将使 python 认为它正在处理一个元组。 I propose the following solution using pythons format function:我使用pythons format函数提出以下解决方案:

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

The {} parts in the string are placeholders that are replaced with the arguments in the parenthesis through the format function.字符串中的{}部分是占位符,通过format函数替换为括号中的参数。 They are replaced in order, so the first one is replaced with self.__name , etc.它们按顺序替换,因此第一个替换为self.__name等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM