这一行与“str”(self)相关的代码是什么意思?

2024-05-13 20:04:11 发布

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

帮助我理解object在这行中的含义:s = ' ' + object.__str__(obj)。我没有看到代码中任何地方引用object,它是一个特殊的关键字吗?在这种情况下是什么意思?你知道吗

指向完整代码的链接:http://greenteapress.com/thinkpython2/code/GoodKangaroo.py

我不能绕着那条线转

def __str__(self):
        """Return a string representaion of this Kangaroo.
        """
        t = [ self.name + ' has pouch contents:' ]
        for obj in self.pouch_contents:
            s = '    ' + object.__str__(obj)
            t.append(s)
        return '\n'.join(t)

Tags: 代码selfobjhttpobject链接地方contents
3条回答

object指的是内置基类,它是一个对象。在Python REPL中键入object可以提供以下功能。。。你知道吗

>>> object
<class 'object'>

它是python标准作用域中包含的基类。你知道吗


这里,这是only reference I can actually find in the docs.

object

Any data with state (attributes or value) and defined behavior (methods). Also the ultimate base class of any new-style class.


I FOUND IT!

class object Return a new featureless object. object is a base for all classes. It has the methods that are common to all instances of Python classes. This function does not accept any arguments.

^{}是python的基类。你知道吗

在本例中,代码正在调用^{},它将使用object的方法将obj转换为字符串。这将调用^{},它将打印出对象的“正式”表示。你知道吗

对于字符串,这将是'[string contents]'(用字符串的实际内容替换[string contents]),对于一般对象,这将是<[object name] at [address]>(同样用对象的实际名称和地址替换[object name][address])。你知道吗

注意:object.__str__(obj)str(obj)将返回不同的结果,因为object.__str__(obj)最终将调用repr(obj)。你知道吗

这行代码是一种将obj转换成字符串的方法,方法是调用基类型object的默认__str__方法,该方法生成一个包含类名和内存中实例地址的字符串,例如<Kangaroo instance at 0xAABBCC>。你知道吗

通常,人们会使用str(obj),但在这种情况下,如果obj是另一个Kangaroo,那么Kangaroo中定义的相同__str__()方法将被递归调用,从而导致生成类似这样的内容:

foo = Kangaroo('foo')
bar = Kangaroo('bar')
baz = Kangaroo('baz')

baz.put_in_pouch(1)
bar.put_in_pouch(baz)
foo.put_in_pouch(bar)

# Result of print str(foo)

foo has pouch contents:
    bar has pouch contents:
    baz has pouch contents:
    1

相反,使用object.__str__()可以避免递归调用该方法,并给出:

# Result of print str(foo)

foo has pouch contents:
    <__main__.Kangaroo instance at 0x7fc3a864d128>

相关问题 更多 >