Search code examples
pythonprintingprivate

python, __str__ a private variable


I am trying to work with private variables so made this test case.

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)

the output is:

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)

Is the error because it's private? Because that doesn't make sense to me because the getA() works.


Solution

  • The __str__() function should return a string, not print one.

    The error you're getting is that str(x) expects x.__str__() to return a string, while yours returns nothing (NoneType).