0

i am new to python from java.

In java we would have something like

public void func1()
{
    func2();
}

private void func2(){}

However, in python i would like the equivalent

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

def func2(str):
    pass

It throws me an error of takes exactly 1 argument(2 given)

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.

How do i exactly resolve this situation.

aceminer
  • 4,089
  • 9
  • 56
  • 104
  • Are these in a class or just functions in the global namespace? – mgilson Jan 30 '15 at 01:08
  • 1
    There are no real private methods in python. http://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private – Padraic Cunningham Jan 30 '15 at 01:13
  • Note, you could change your `@classmethod` to an `@staticmethod` and the code would likely work (although I can't guarantee it as I can't see the whole example class :-) – mgilson Jan 30 '15 at 01:34

3 Answers3

5

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
2

Another possibility is that you want func2 to be private to (only exist in scope of) func1. If so, you can do this:

def func1(self, args):
    def func2(args):
        # do stuff
        pass
    return func2(args)
dylrei
  • 1,728
  • 10
  • 13
1

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
Lex Berezhny
  • 512
  • 3
  • 15