0

Why this code doesn't work ?

#!/usr/bin/python2
from xmlrpclib import ServerProxy
class ServerProxy1(ServerProxy):
    def __str__(self):
        return str(self.__host)


proxy = ServerProxy1("http://workshop:58846/")
print proxy

Original_str_:

    def __repr__(self):
        return (
            "" %
            (self.__host, self.__handler)
            )

    __str__ = __repr__

Result:

  File "/usr/lib/python2.7/xmlrpclib.py", line 793, in close
    raise Fault(**self._stack[0])
xmlrpclib.Fault: :method "_ServerProxy1__host.__str__" is not supported'>
Bdfy
  • 23,141
  • 55
  • 131
  • 179

1 Answers1

3

The answer is hiding in this SO post

The member self.__host in class ServerProxy was declared using the double-underscore naming that's meant to indicate that it shouldn't be accessed by derived classes. To do this, the interpreter mangles its name internally in the form _className__memberName -- Python isn't C++, and treats that 'private' notation as a strong hint, not as an absolute prohibition.

When code is written with the double underscore prefix, you can access it like

class ServerProxy1(ServerProxy):
    def __str__(self):
        return str(self._ServerProxy__host)

..but you shouldn't be surprised if a future version of the ServerProxy class changes its internal implementation and breaks your code.

Community
  • 1
  • 1
bgporter
  • 35,114
  • 8
  • 59
  • 65
  • 2
    Double-underscore name obfuscation for the loss! It's really the only feature about Python I truly hate. Further reading here: http://docs.python.org/tutorial/classes.html#private-variables – jathanism Apr 12 '11 at 14:18