因此,作为“像计算机科学家一样思考”中问题 17.6 的一部分,我编写了一个名为 Kangaroo 的类:
class Kangaroo(object):
def __init__(self, pouch_contents = []):
self.pouch_contents = pouch_contents
def __str__(self):
'''
>>> kanga = Kangaroo()
>>> kanga.put_in_pouch('olfactory')
>>> kanga.put_in_pouch(7)
>>> kanga.put_in_pouch(8)
>>> kanga.put_in_pouch(9)
>>> print kanga
"In kanga's pouch there is: ['olfactory', 7, 8, 9]"
'''
return "In %s's pouch there is: %s" % (object.__str__(self), self.pouch_contents)
def put_in_pouch(self, other):
'''
>>> kanga = Kangaroo()
>>> kanga.put_in_pouch('olfactory')
>>> kanga.put_in_pouch(7)
>>> kanga.put_in_pouch(8)
>>> kanga.put_in_pouch(9)
>>> kanga.pouch_contents
['olfactory', 7, 8, 9]
'''
self.pouch_contents.append(other)
让我发疯的是,我希望能够编写一个字符串方法,该方法将通过下面的单元测试__str__
。我现在得到的是:
In <__main__.Kangaroo object at 0x4dd870>'s pouch there is: ['olfactory', 7, 8, 9]
基本上,我想知道是否有一些我可以在 kanga = Kangaroo 上执行的函数,这样函数的输出就是这 5 个字符,即 function(kanga) -> "kanga"。
有任何想法吗?
编辑:
阅读第一个答案让我意识到有一种更简洁的方式来问我原来的问题。有没有办法重写__init__
以使以下代码在编写时有效?
>>> somename = Kangaroo()
>>> somename.name
'somename'