【问题标题】:How to define method in class that can only be called from __init__ method如何在类中定义只能从 __init__ 方法调用的方法
【发布时间】:2020-05-14 19:55:46
【问题描述】:

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

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)

【问题讨论】:

    标签: python python-3.x class methods


    【解决方案1】:

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

    class Test:
        def __init__(self):
            self.__do_something  # Should work
    
        def __do_something(self):
            # do something
    
    test = Test()
    test.__do_something()
    

    【讨论】:

      【解决方案2】:

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

      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
      

      输出:

      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'
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2021-07-21
          • 2018-01-03
          • 1970-01-01
          • 1970-01-01
          • 2013-10-12
          • 2017-12-13
          • 2023-03-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多