简体   繁体   English

如何在python中定义等效的私有方法

[英]how to define equivalent of private method in python

i am new to python from java. 我是来自Java的python新手。

In java we would have something like 在java中,我们将有类似

public void func1()
{
    func2();
}

private void func2(){}

However, in python i would like the equivalent 但是,在python中,我想要等效的

def func1(self):
    self.func2("haha")
    pass

def func2(str):
    pass

It throws me an error of takes exactly 1 argument(2 given) 它给我带来一个错误,该错误恰好需要1个参数(给定2个)

I have checked for solutions such as using 我已经检查了解决方案,例如使用

def func1(self):
    self.func2("haha")
    pass

@classmethod 
def func2(str):
    pass

but it does not work 但它不起作用

Taking out the self in func2 makes the global name func2 not defined. 在func2中取出self会使全局名称func2没有定义。

How do i exactly resolve this situation. 我该如何解决这种情况。

Usually you do something like this: 通常,您会执行以下操作:

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.

Note that python has no true privacy. 请注意,python没有真正的隐私。 If a user wants to call your method, they can. 如果用户想调用您的方法,则可以。 It's just a fact of life that is described by the mantra "We're all consenting adults here" . 口头禅所描述的只是生活中的事实: “我们都同意这里的成年人” However, if they call your method that is prefixed with an underscore, they deserve any breakages that they cause. 但是,如果他们调用带下划线前缀的方法,则应避免造成的任何损坏。

Also note that there are two levels of privacy: 另请注意,隐私有两个级别:

def _private_method(self, ...):  # 'Normal'
    ...

def __private_with_name_mangling(self, ...):  # This name gets mangled to avoid collisions with base classes.
    ...

More info can be found in the tutorial . 可以在教程中找到更多信息。

Another possibility is that you want func2 to be private to (only exist in scope of) func1. 另一种可能性是您希望func2对func1私有(仅存在于func1的范围内)。 If so, you can do this: 如果是这样,您可以这样做:

def func1(self, args):
    def func2(args):
        # do stuff
        pass
    return func2(args)

Try this: 尝试这个:

class Foo:
  def method(self):
    self.static_method("haha")

  @classmethod 
  def static_method(clazz, str):
     print(str)

>>> Foo().method()
haha
>>> Foo.static_method('hi')
hi

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

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