python – Is there a way to specify a method that can only be called from within the class?

Question: Question:

I'm using Python 3.4.3.

While creating my own module, I cut out the common processing of the instance method of the class and make it another instance method, but I want to prevent the latter instance method from being called other than the above instance method (or) I want to see when I look at the code that I only use it for the instance methods mentioned above)

class testclass:
    def __init__(self):
        pass

    def get_power_two(self, number):  # 2のnumber乗を返す
        answer = 1
        for i in range(0, number):
            answer = self.twice(answer)
        return answer

    def twice(self, answer):  # get_power_two以外からは呼び出されない
        return 2*answer

A = testclass()
print(A.get_power_two(4))  # 16
A.twice(2)  # これがエラーになってほしい

In the above code, a part of the process of get_power_two() is cut out to an instance method called twice() , which can be called A.twice(2) . I'd like to make it clear that this method isn't or shouldn't be called by anyone other than a method in the same class. Is there a good way?
Thank you.

Answer: Answer:

Let's name the method _twice .
In Python, add _ to indicate that you don't want it to be used from the outside.
It may be used ignoring it, but that is the responsibility of the user.

There is also a way to add __ , but it is not recommended because it will be too inconvenient.

Scroll to Top