Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> '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 __ ("dunder methods, dunder attributes").

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading