Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling non-static method from static one in Python

Tags:

python

oop

I can't find if it's possible to call a non-static method from a static one in Python.

Thanks

EDIT: Ok. And what about static from static? Can I do this:

class MyClass(object):

    @staticmethod
    def static_method_one(cmd):
    ...

    @staticmethod
    def static_method_two(cmd):
        static_method_one(cmd)
like image 492
legesh Avatar asked Sep 06 '09 12:09

legesh


1 Answers

After the other answers and your follow-up question - regarding static method from static method: Yes you can:

>>> class MyClass(object):
    @staticmethod
    def static_method_one(x):
        return MyClass.static_method_two(x)
    @staticmethod
    def static_method_two(x):
        return 2 * x


>>> MyClass.static_method_one(5)
10

And, in case you're curious, also yes for class method from class method (easy to test this stuff in the interpreter - all this is cut and pasted from Idle in 2.5.2) [**EDITED to make correction in usage pointed out by others**]:

>>> class MyClass2(object):
    @classmethod
    def class_method_one(cls, x):
        return cls.class_method_two(x)
    @classmethod
    def class_method_two(cls, x):
        return 2 * x


>>> MyClass2.class_method_one(5)
10
like image 118
Anon Avatar answered Oct 21 '22 02:10

Anon