Search code examples
python-3.xstatic-methodspython-decorators

Python 3.4 : can static methods only be called from an instance?


I am trying to call a @staticmethod method from within a class to initialize a class variable as shown here :

class Test:
    @staticmethod
   def get_bit_count():
       return 8
   num = get_bit_count()

But this immediately throws the following error : TypeError: 'staticmethod' object is not callable.

However, the following code works just fine :

class Test:
    @staticmethod
    def get_bit_count():
        return 8
    num = None
    def __init__(self):
        self.num = self.get_bit_count()

print(Test.get_bit_count())
print(Test().num)

The method can be called and the variable num gets set correctly with the following output :

8
8

But with that code I now need to instantiate the class to do so.

Is there a way to allow me to use Test.num and get 8 not None without instantiating the class ? I wish to do so to avoid redundancy by having only one variable in the method get_bit_count() to change when I whish to update my code.


Solution

  • Static methods, as stated in the documentation for staticmethod can only be called on the class or an instance.

    You could use a normal method, though. If you want to be able to call it also on an instance, just let it accept any number of arguments:

    class Test:
        def get_bit_count(*args, **kwargs):
            return 8
    
        num = get_bit_count()
    
    
    print(Test.num)
    # 8
    
    t = Test()
    print(t.get_bit_count())
    # 8