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()