繁体   English   中英

如何在 class 中定义只能从 __init__ 方法调用的方法

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

我有一个简单的 Python class,带有构造函数和方法。 我希望该方法只能从构造函数中调用,而不是在 class 定义之外。 在 Python 中有没有办法做到这一点? 我知道我可以通过在构造函数中定义一个 function 来做到这一点,但我不想这样做。

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)

您需要在 do_something(self) 前面加上双下划线。 代码如下。

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

    def __do_something(self):
        # do something

test = Test()
test.__do_something()

是的,您可以使用双下划线前缀标记方法:

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'

要使其在 python 中成为“私有”,只需在其名称前加上 __。 不过,它不会是真正的私密。 只是名称略有不同。 您仍然可以通过在 class 的 object 上运行 dir 来访问它,一旦您知道名称,您就可以使用它在 class 之外调用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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