AskingQuestions
AskingQuestions

Reputation: 33

Make a function not accessible when using my API

I am working on an API for my website, I will release the API as a package for Python. How can I make a function not accessible from the class object ? I have tried to use classmethod but it seems not to work, I still can access the function from an outside Python file.

main.py

class MyClass:
   def __init__(self):
       self.my_var = 5
   
   @classmethod
   def dont_access_me(self) -> str:
       return 'Dont Access Me'

second.py

from main import MyClass

instance = MyClass()
print(instance.dont_access_me()) # valid

Upvotes: 1

Views: 989

Answers (3)

gelonida
gelonida

Reputation: 5630

Python does not really have private methods.

What is however common practice is to prefix methods with an underscore if you want to indicate, that users should not use this function and that users cannot expect this function to exist or to have the same signature in a future release of your API.

if you have:

class MyClass:
   def __init__(self):
       self.my_var = 5

   def amethod(self):
       rslt = self._dont_access_me()

   def _dont_access_me(self) -> str:
       return 'Dont Access Me'

instance = MyClass()

then users know, that they can use.

instance.amethod(), but that they should not use instance._dont_access_me()

classmethods are like in most other programming languages something completely different. They are used for methods, that can be called without having an instance, However they can also be called if you have an instance.

An example would be:

class AClass:
    instance_count = 0

    def __init__(self):
        cls = self.__class__
        cls.instance_count += 1
        self.idx = cls.instance_count

    @classmethod
    def statistics(cls):
        print("So far %d objects were instantiated" %
              cls.instance_count)


a = AClass()
b = AClass()
AClass.statistics()

# However you can also access a classmethod if you have an instance
a.statistics()

Upvotes: 1

darkwing
darkwing

Reputation: 160

I'm not sure if this is what you're looking for, but you could make it a private method, something like this:

def _dont_access_me(self):
     return 'Dont Access Me'

technically, it would still be accessible, but it at least lets users know it's intended as a private method

Upvotes: 0

Rusty Widebottom
Rusty Widebottom

Reputation: 984

You cannot make a class method truly private. There is a good discussion on this subject in this question: Why are Python's 'private' methods not actually private?

Upvotes: 0

Related Questions