Python类输出十六进制值而不是list,不知道为什么?

2024-04-24 01:22:31 发布

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

class SList:
    def __init__(self):
        self.s1 = ['hey']
    def take(self, item):
        self.s1 += [item]
        return self.s1
    def size(self):
        size = len(self.s1)
        return size

if __name__ == "__main__" :
    s1 = SList()
    print('hello')
    s1.take(33)
    s1.take(42)
    s1.take(55)
    s1.size()
    print(s1)
    print(s1.size())

不太熟悉类,写这篇文章更多的是为了证明概念,所以我可以熟悉它。我似乎不明白为什么这个结果是:

hello

<__main__.SList object at 0x3323ed0>

4

hello4是我想要的方式,但是我似乎得到了s1的十六进制值,当我需要s1输出时:['hey', 33, 42, 55]

哇能让s1输出正确的列表吗?在


Tags: selfhellosizelenreturninitmaindef
3条回答

添加^{}^{}的重写:

class SList:
    def __init__(self):
        self.s1 = ['hey']

    def take(self, item):
        self.s1 += [item]
        return self.s1

    def size(self):
        size = len(self.s1)
        return size

    def __repr__(self):
        return repr(self.s1)

if __name__ == "__main__" :
    s1 = SList()
    print('hello')
    s1.take(33)
    s1.take(42)
    s1.take(55)
    s1.size()
    print(s1)
    print(s1.size())

这就足够了:

hello

['hey', 33, 42, 55]

4

来自documentation关于__repr__

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines repr() but not str(), then repr() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

为了完整起见,您还可以重写^{}

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from repr() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

我认为您应该重写str方法来输出您想要的。在

而不是

print(s1)

使用

^{pr2}$

与原始情况一样,您正在打印SList类的实例对象。在

相关问题 更多 >