Reputation: 152
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?
Upvotes: 0
Views: 536
Reputation: 1
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")
Upvotes: 0
Reputation: 117
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.
Upvotes: 2