0

I have follow class:

class Communicator(Thread):

  __callback = {
    "sender_callback":"__Out",
    "listener_callback":"__In"
  }

  def __init__(self, direction):
    Thread.__init__(self)

  def run(self):
    getattr(self, self.__callback["sender_callback"])(data)  # callback is OK
    ''' some many source code '''
    getattr(self, self.__callback["listener_callback"])(data)  # AttributeError: 'Communicator' object has no attribute '__servicePercentSetIn'
    getattr(self, "_Communicator"+self.__callback["listener_callback"])(data)  # callback OK

  def __Out(self, data):
    pass

  def __In(self, data):
    pass

Why does getattr with listener_callback raise an exception, when getattr with sender_callback is works fine. Also, why does the third getattr need a class name prefix?

all whitespaces are space, not tab

Python 2.7 and 3.5

Nihal Rp
  • 484
  • 6
  • 15
  • Also related: [Why does the “name” parameter to __setattr__ include the class, but __getattr__ doesn't?](http://stackoverflow.com/q/2386418/216074). Note the following sentence from the accepted answer there: *“If you don't need name mangling, don't use double undescore.”* – poke Nov 20 '16 at 00:21
  • In general, what you are seeing here is name wrangling. If you access `self.__something` within the class directly, Python takes care of modifying the name properly. All other uses (especially with `getattr`) will have to apply the name wrangling themselves. It’s best not to use double underscores in situations like this. I assume the sender callback works in your example because the *real* code is not using double underscore names there. (The example code throws the exception already for the first name) – poke Nov 20 '16 at 00:23
  • thanks for your answers, i searched five hours this solution – user3133528 Nov 20 '16 at 00:45

0 Answers0