Search code examples
pythonpython-classpython-object

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


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


Solution

  • 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