[英]How to get a class to print out multiple parameters (__str__ function question)
I'm creating a class that prints out its contents using the str () function.我正在创建一个 class,它使用str () function 打印出其内容。 However, I can only seem to be able to get it to print out one of the parameters?但是,我似乎只能让它打印出其中一个参数? When I ask it to return self.num as well as self.word it throws an error.当我要求它返回 self.num 和 self.word 时,它会引发错误。
Would anyone be able to help me on this?有人可以帮助我吗?
class Test:
def __init__ (self, word, num):
self.word = word
self.num = num
def __str__(self):
return self.word, self.num
a = Test('Word', '10')
print(a)
The __str__
method is expected to return a single string. __str__
方法应返回单个字符串。 To show several variables, concatenate (via +
if they are strings) or format them (via f-string literals , format string templates , or printf %-formatting ) into a single string.要显示多个变量,请连接(通过+
如果它们是字符串)或将它们格式化(通过f-string literals 、 format string templates或printf %-formatting )成单个字符串。
class Test:
def __init__ (self, word, num):
self.word = word
self.num = num
def __str__(self):
# f-string literal - ``{...}`` are replacement fields
return f'{self.word} => {self.num}'
a = Test('Word', '10')
print(a) # Word => 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.