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.

3
  • Are these in a class or just functions in the global namespace? Commented Jan 30, 2015 at 1:08
  • 1
    There are no real private methods in python. stackoverflow.com/questions/70528/… Commented Jan 30, 2015 at 1: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 :-) Commented Jan 30, 2015 at 1:34

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

2 Comments

You should be able to call your classmethod as self.func2 from within func1.
Thanks, I've updated the example. Also added how to call func1 as a method and calling func2 as a 'static method'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.