Calling private function within the same class python

前端 未结 2 979
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 03:59

How can i call a private function from some other function within the same class?

class Foo:
  def __bar(arg):
    #do something
  def baz(self, arg):
    #w         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 04:22

    There is no implicit this-> in Python like you have in C/C++ etc. You have to call it on self.

    class Foo:
         def __bar(self, arg):
             #do something
         def baz(self, arg):
             self.__bar(arg)
    

    These methods are not really private though. When you start a method name with two underscores Python does some name mangling to make it "private" and that's all it does, it does not enforce anything like other languages do. If you define __bar on Foo, it is still accesible from outside of the object through Foo._Foo__bar. E.g., one can do this:

    f = Foo()
    f._Foo__bar('a')
    

    This explains the "odd" identifier in the error message you got as well.

    You can find it here in the docs.

提交回复
热议问题