簡體   English   中英

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

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

我是來自Java的python新手。

在java中,我們將有類似

public void func1()
{
    func2();
}

private void func2(){}

但是,在python中,我想要等效的

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

def func2(str):
    pass

它給我帶來一個錯誤,該錯誤恰好需要1個參數(給定2個)

我已經檢查了解決方案,例如使用

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

@classmethod 
def func2(str):
    pass

但它不起作用

在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.

請注意,python沒有真正的隱私。 如果用戶想調用您的方法,則可以。 口頭禪所描述的只是生活中的事實: “我們都同意這里的成年人” 但是,如果他們調用帶下划線前綴的方法,則應避免造成的任何損壞。

另請注意,隱私有兩個級別:

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

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

可以在教程中找到更多信息。

另一種可能性是您希望func2對func1私有(僅存在於func1的范圍內)。 如果是這樣,您可以這樣做:

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

嘗試這個:

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