python,__str__一个私有变量

Eas*_*led 0 python printing private

我正在尝试使用私有变量,因此制作了这个测试用例.

class X():
    def __init__(self):
        self.__a = 0
    def __str__(self):
        print(self.getA())
    def getA(self):
        return self.__a
x = X()
print(x.getA())
print(str(x.getA()))
print(x)
Run Code Online (Sandbox Code Playgroud)

输出是:

0
0
0
Traceback (most recent call last):
  File "/Users/lego90511/Documents/workspace/dummy/dummy.py", line 150, in <module>
    print(x)
TypeError: __str__ returned non-string (type NoneType)
Run Code Online (Sandbox Code Playgroud)

错误是因为它是私有的吗?因为这对我来说没有意义,因为getA()有效.

Bil*_*nch 9

该__str__()函数应该返回一个字符串,而不是打印一个.

你得到的错误是str(x)期望x.__str__()返回一个字符串,而你的返回什么(NoneType).