1

I need a function which I will use only inside my class. Is it ok to define it like other methods or it's better to hide it somewhere?

class Test:

    def __init__(self,a,b):
        self.a=a
        self.b=b

    def sayhi(self):
        print('hi')

    def printa(self,c):
        self.sayhi()
        print('A+C=',self.a+c)

    def printb(self,c):
        self.sayhi()
        print('B+C=',self.b+c) 

2 Answers 2

4

Unlike java and some other object oriented languages Python does not have private methods. You can just add an underscore before the method name to indicate that it is a private method. NB: this has meaning only to you and is ignored by the interpreter. The method can still be called outside the class

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to Stackoverflow - great answer.
3

Make it a "private" function

Use the python convention for making a function "private" by contract.

See https://dbader.org/blog/meaning-of-underscores-in-python

class Test:
    def __init__(self,a,b):
        self.a=a
        self.b=b

    def _sayhi(self):
        print('hi')

    def printa(self,c):
        self._sayhi()
        print('A+C=',self.a+c)

    def printb(self,c):
        self._sayhi()
        print('B+C=',self.b+c) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.