为什么getattr()在方法存在时引发异常?

时间:2016-11-20 00:14:28

标签: python

我跟着上课:

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

当带有sender_callback的getattr工作正常时,为什么带有listener_callback的getattr会引发异常。另外,为什么第三个getattr需要一个类名前缀?

所有空格都是空格,而不是标签

Python 2.7和3.5

0 个答案:

没有答案