Keverly
Keverly

Reputation: 518

AttributeError when trying to access class methods that do exist

I am trying to write tests for class methods but when I call them I get an AttributeError which complains the methods don't exist.

class Foo:
    @staticmethod
    def __method_to_test(x)
        return x ** 2

Foo.__method_to_test(3)

The last line results in the following: AttributeError: type object 'Foo' has no attribute '__method_to_test'

Why can't I call the method?

Upvotes: 2

Views: 978

Answers (1)

Keverly
Keverly

Reputation: 518

Thanks to Sven Eberth, collecting their responses here.

Python Renames Methods That Start With A Double Underline

Starting a method with a double underline causes python to do something called name mangling which causes the method to be renamed from __method_to_test to _Foo__method_to_test.

Call the function like this:

Foo._Foo__method_to_test(3)

Upvotes: 3

Related Questions