[英]Printing Python __str__ from an object
I have actually finished this exercise (almost) but am just stuck on a tiny problem with __str__
which is inside an object. 我实际上已经完成了该练习(几乎),但是只是陷入了对象内部
__str__
一个小问题。 If i do this 如果我这样做
elif choice == "9":
try:
for i in sworm:
print(i)
except TypeError:
None`
Then it will only print out the details of the first object in my list (only 2 objects in there) eg -- sworm = [crit,crit1]
然后,它将仅打印出列表中第一个对象的详细信息(其中只有2个对象),例如
sworm = [crit,crit1]
When I tried this 当我尝试这个
elif choice == "9":
try:
print(sworm)
except TypeError:
None
Then I get:- 然后我得到:
[<__main__.Critter object at 0x02B54AD0>, <__main__.Critter object at 0x02B5B190>]
Here is the first half of my Object 这是我对象的前半部分
class Critter(object):
"""A virtual pet"""
def __init__(self, name, hunger = random.randint(1,50), boredom = random.randint(1,50)):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self):
self.hunger += 1
self.boredom += 1
def __str__(self):
print ("Critter object\n")
print (self.name)
print (self.hunger)
print (self.boredom)
Thanks in advance. 提前致谢。
A Python list always shows the contents as representations, calling repr()
on the objects. Python列表始终将内容显示为表示形式,并在对象上调用
repr()
。
You can hook into that by specifying a __repr__
method as well. 您也可以通过指定
__repr__
方法来加入。 Alternatively, don't print the list directly, but only the contents: 或者,不要直接打印列表,而只打印内容:
for elem in sworm:
print(elem)
or join them as a long string: 或将它们作为长字符串加入:
print(', '.join(map(str, sworm)))
Do make sure you actually return a value from your __str__
method though: 但是,请确保您确实从
__str__
方法返回了一个值:
def __str__(self):
return "Critter object\n{}\n{}\n{}".format(self.name, self.hunger, self.boredom)
because it is the return value that is printed by print()
. 因为它是由
print()
的返回值 。
The problem is this: 问题是这样的:
print ("Critter object\n")
print (self.name)
print (self.hunger)
print (self.boredom)
See, the __str__ method shouldn't actually print anything. 可见,__str__方法实际上不应打印任何内容。 Instead, it should return what it wants to be printed.
相反,它应该返回要打印的内容。 So, you need to do this:
因此,您需要这样做:
return "Critter object\n\n" + self.name + '\n' + self.hunger + '\n' + self.boredom
Alternatively if you do not want to hard code your str properties you can do it like this 另外,如果您不想对str属性进行硬编码,则可以这样做
def __str__(self):
return ', '.join(['{key}={value}'.format(key=key, value=self.__dict__.get(key)) for key in self.__dict__])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.