简体   繁体   中英

How to define method in class that can only be called from __init__ method

I have a simple Python class, with a constructor and a method. I want the method to only be able to be called from the constructor, and not outside the class definition. Is there any way to do this in Python? I know I can do this by defining a function inside the constructor, but I don't want to do that.

class Test:
    def __init__(self):
        self.do_something  # Should work

    def do_something(self):
        # do something

test = Test()
test.do_something()  # Should not work (Should not be a recognized method)

You need to preface do_something(self) with a double underscore. The code is below.

class Test:
    def __init__(self):
        self.__do_something  # Should work

    def __do_something(self):
        # do something

test = Test()
test.__do_something()

Yes, you can mark methods with a double underscore prefix:

class Test:
    def __init__(self):
        self.__do_something()  # This works

    def __do_something(self):
        print('something')

test = Test()
test.__do_something()  # This does not work

Output:

something
Traceback (most recent call last):

  File "something.py", line 11, in <module>
    test.__do_something()  # This does not work
AttributeError: 'Test' object has no attribute '__do_something'

To make it 'private' in python just prepend __ to its name. It won't be truly private though. It will just be by a slightly different name. You can still access it by running dir on an object from the class and once you know the name you can use it to call it outside the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM