[英]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.我有一个简单的 Python class,带有构造函数和方法。 I want the method to only be able to be called from the constructor, and not outside the class definition.
我希望该方法只能从构造函数中调用,而不是在 class 定义之外。 Is there any way to do this in Python?
在 Python 中有没有办法做到这一点? I know I can do this by defining a function inside the constructor, but I don't want to do that.
我知道我可以通过在构造函数中定义一个 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)
You need to preface do_something(self) with a double underscore.您需要在 do_something(self) 前面加上双下划线。 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: 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.要使其在 python 中成为“私有”,只需在其名称前加上 __。 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.
您仍然可以通过在 class 的 object 上运行 dir 来访问它,一旦您知道名称,您就可以使用它在 class 之外调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.