0

What is the correct way and best practice to call a private method from within a static method in python 3.x? See example below:

class Class_A:
    def __init__(self, some_attribute):
        self.some_attr = some_attribute

    def __private_method(arg_a):
        print(arg)
    
    @staticmethod
    def some_static_method(arg_a):
        __private_method(arg_a) # "__private_method" is not defined

Now, if I instantiate a Class_A object and call the static method:

my_instance = Class_A("John Doe")
my_instance.some_static_method("Not his real name")

I get a NameError: NameError: name '__private_method' is not defined

Mehdi RH
  • 322
  • 1
  • 7
  • 18
  • Static method is independent of instances. How do you expect it to access the private method of instance? – Mechanic Pig Jan 01 '23 at 09:53
  • Even if I add `@staticmethod` atop the private method, it remains inaccessible? – Mehdi RH Jan 01 '23 at 09:54
  • 1. There is no such thing as `@static_method`, you meant `@staticmethod` 2. Don't use leading double underscore. – DeepSpace Jan 01 '23 at 09:55
  • the problem is that you are trying to access `__private_method` as a global method but it's part of `Class_A` if you want to call it you need to use the Class_A or an instance of it. ``` class Class_A: def __init__(self, some_attribute): self.some_attr = some_attribute @staticmethod def __private_method(arg_a): print(arg_a) @staticmethod def some_static_method(arg_a): Class_A.__private_method(arg_a) ``` i know the output is messed up but it will work – zaki98 Jan 01 '23 at 10:02

0 Answers0