-2

I have a class

class Test(object):
    @staticmethod
    def f(str):
      print(str)
    a = f('aaa')

How to do it properly? I have 'staticmethod' object is not callable error. classmethod attribute gets error too. Please don't advise to call outside from class, I want it to be implemented in this way.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mimic
  • 4,897
  • 7
  • 54
  • 93
  • 1
    Does this answer your question? [Calling class staticmethod within the class body?](https://stackoverflow.com/questions/12718187/calling-class-staticmethod-within-the-class-body) – Hymns For Disco Feb 26 '20 at 19:47

3 Answers3

0

From the documentation:

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

So you need to call it either inside another function in the class or create an object instance from the class. For exmaple:

class Test(object):

    def __init__(self):
        self.a = self.f('aaa')

    @staticmethod
    def f(str):
      print(str)
pms
  • 944
  • 12
  • 28
  • 1
    Please edit your answer with a textual explanation of the code snippet and explain how it answers the question – chevybow Feb 26 '20 at 22:54
0
class Test(object):
   @staticmethod
   def f(str):
     print(str)
   a = f.__func__('aaa')

See 'staticmethod' object is not callable for more detail.

codingatty
  • 2,026
  • 1
  • 23
  • 32
-2

To call it from inside the class, use self keyword.

a = self.f('aaa')
fullstack
  • 11
  • 3