0

I'm working on an already established Python 2.7 Project, there needs to be some modification and I'm still relatively new to Python, here's what I did:

I have 2 functions in the same class, one is @staticmethod and other is a @classmethod. I need to call @classmethod from inside @staticmethod like -

class ABC(object):

    @classmethod
    def classm(self, name):
        ...
    
    
    @staticmethod
    def staticm(freq):
        ...
        ...
        classm("sample")

The above piece of code doesn't work, so I converted the staticmethod to classmethod and then it worked fine (using 'self' in correct places)

Can someone please explain if we can call classmethod from staticmethod (most probably it seems that I don't know the syntax), if not, is there a better workaround without converting?

Achal Sharma
  • 152
  • 1
  • 11
  • Use the name of the class: `ClassName.class_method(...)` or use the class object which is passed into class methods. – Christian Dean May 26 '21 at 07:28
  • duplicate of https://stackoverflow.com/questions/1385546/calling-non-static-method-from-static-one-in-python – Francesco Pegoraro May 26 '21 at 07:34
  • If you need a reference to the class it is in, the `@staticmethod` decorator is not the right choice. You have class method then. – Klaus D. May 26 '21 at 07:44
  • Does this answer your question? [Calling non-static method from static one in Python](https://stackoverflow.com/questions/1385546/calling-non-static-method-from-static-one-in-python) – Francesco Pegoraro May 26 '21 at 07:44

2 Answers2

2

Firstly, I would like to say that please try to not use self in class methods as the community uses self for passing the instance and so it may confuse the reader use cls instead:

class ABC:
    @classmethod
    def classm(cls, name):
     ...

You can use ABC.classm("Sample"). Example:

class ABC():
    @classmethod
    def classm(cls, name):
        print(name)

    @staticmethod
    def staticm(freq):
        ABC.classm(freq)


test = ABC()
test.staticm("Vedant")

if you run this code you will see that Vedant is getting printed and that the static method is calling the class method to do so.

0

class method take first argument class, while static has no problem.

class Test:
    @classmethod
    def first(cls, a):
        return a+"From first"

    @staticmethod
    def sec(a):
        print(Test.first(a), "+from 2")


a=Test
print(a.first("hello"))
a.sec("hello")