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?

4
  • Use the name of the class: ClassName.class_method(...) or use the class object which is passed into class methods. Commented May 26, 2021 at 7:28
  • duplicate of stackoverflow.com/questions/1385546/… Commented May 26, 2021 at 7: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. Commented May 26, 2021 at 7:44
  • Does this answer your question? Calling non-static method from static one in Python Commented May 26, 2021 at 7:44

2 Answers 2

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.

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

Comments

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.