Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+8 votes
asked in CSC201 Spring 2021 by (1 point)

3 Answers

+6 votes

Any method name that has one to two underscore before it will be considered as 'private method' by Python.

So what you do it just simply like this:

def _methodName(self, other parameter):
answered by (1 point)
+5 votes

to define a private method, you can prefix the method name with double underscore “__”

# Creating a Base class 
class Base: 
  
    # Declaring public method
    def fun(self):
        print("Public method")
  
    # Declaring private method
    def __fun(self):
        print("Private method")
answered by (1 point)
+5 votes

Several other people have posted good answers explaining how. I'll just add a little note:

Technically, Python doesn't have any methods that are truly "private" -- i.e. that can't be called by outside client code if the client REALLY wants to.

The use of underscores at the beginning of method names is more of a polite convention in Python, to tell other programmers -- "hey, this _method() is something that's only useful/used by code INSIDE of this class, and you really shouldn't try to call it from your own program, because it either isn't useful for you, or you might mess stuff up if you do!"

If you take CSC 202 and learn some Java programming, you'll learn about real private methods that other code outside of the class the method is in CANNOT call. (In general, Java is usually more strict than Python about defining and following rules... like in Java, each variable gets a declared TYPE, and it can only store data values of that type.)

answered by (3.5k points)
...