我是java的新手.
在java中我们会有类似的东西
public void func1()
{
func2();
}
private void func2(){}
Run Code Online (Sandbox Code Playgroud)
但是,在python我想要相当于
def func1(self):
self.func2("haha")
pass
def func2(str):
pass
Run Code Online (Sandbox Code Playgroud)
它抛出了一个错误,只需要1个参数(给定2个)
我已经检查了使用等解决方案
def func1(self):
self.func2("haha")
pass
@classmethod
def func2(str):
pass
Run Code Online (Sandbox Code Playgroud)
但它不起作用
在func2中取出self会使全局名称func2无法定义.
我如何完全解决这种情况.
通常你做这样的事情:
class Foo(object):
def func1(self):
self._func2("haha")
def _func2(self, arg):
"""This method is 'private' by convention because of the leading underscore in the name."""
print arg
f = Foo() # make an instance of the class.
f.func1() # call it's public method.
Run Code Online (Sandbox Code Playgroud)
请注意,python没有真正的隐私.如果用户想要调用您的方法,他们可以.这只是生活中的一个事实,用"我们都同意这里的成年人"的咒语来描述.但是,如果他们将您的方法称为带有下划线的前缀,则他们应该得到它们造成的任何破坏.
另请注意,有两个级别的隐私:
def _private_method(self, ...): # 'Normal'
...
def __private_with_name_mangling(self, ...): # This name gets mangled to avoid collisions with base classes.
...
Run Code Online (Sandbox Code Playgroud)
更多信息可以在教程中找到.
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |