Is there a way to disable some function in python class so that it cannot be used except using it in inside its class?

2.5k Views Asked by At

for example i have myClassFile.py file with code as follow:

class myClass:

    def first(self):
        return 'tea'

    def second(self):
        print(f'drink {self.first()}')

then i have run.py file with code as follow:

from myClassFile import myClass

class_ = myClass()
class_.second()

which when i run will output

>>> 'drink tea'

how to prevent someone to write below code on run.py file or outside myClass ?

class_.first()

so that if they used that method outside myClass class it will be an error or some sort

2

There are 2 best solutions below

2
qkzk On BEST ANSWER

You can add a level of protection around methods and attributes by prefixing them with __.

But you can't make them totally private (as far as I know), there's always a way around, as shown in example below.

class MyClass:
    def __init__(self):
        self.__a = 1

    def __method(self):
        return 2


obj = MyClass()

# obj.__a  # raise an exception
# obj.__method() # raise an exception
print(dir(obj)) # you can see the method and attributes have been renamed !
print(obj._MyClass__a) # 1
print(obj._MyClass__method()) # 2
8
Berlm On

Python does not have support for these. You can mark them private by prefixing them with _, or make it harder to call them by prefixing them with __.

These are called private methods. To make a private variable or a method in python, just prefix it with a __, so def second(self) turns into def __second(self).

This also works for variables and functional programming variables!

class Test:  
    def test(self):
        self.__test()
        
    def __test(self):  
        print('_test')
        
        
x = Test()
x.__test()

gives an error, but x.test() prints _test out successfully!

Note, this can still be run by using x.__Test__test()