簡體   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