2
class Dog(object):
    def __init__(self):
        self.type = 'corgi'
        self.barked = False
    def __bark(self):
        print('__woof')
        self.barked = True
    def _bark(self):
        print('_woof')
        self.barked = True
    def call_method(self, method_name):
        method = getattr(self, method_name)()
d = Dog()
d.call_method('_bark')  # this works
d.call_method('__bark')  # this raise an AttributeError

I have a dog class where I want to use getattr to dynamically find a method under self When I try to find the method name of a class with two underscores is fails but if I use one underscore it works. Why is the double underscore method not seen by getattr?

spacether
  • 2,136
  • 1
  • 21
  • 28

1 Answers1

1

Double underscore methods are name mangled per here: What is the meaning of a single- and a double-underscore before an object name?

If you need to access your methods with getattr make them have no leading underscores, or one underscore.

spacether
  • 2,136
  • 1
  • 21
  • 28