3

In my class I'd like to call a non-member function whose reference is stored in a member variable. My issue is that it tries to pass self to the function as the first argument. How can I avoid this?

class MyClass:
    my_useful_static_function = crcmod.mkCrcFun(0x11021, True)

    def __init__(self):
        # this gets called with the first argument as self :(
        result = self.my_useful_static_function()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Rick
  • 1,240
  • 14
  • 21

2 Answers2

3

Use staticmethod:

class MyClass:
    my_useful_static_function = staticmethod(crcmod.mkCrcFun(0x11021, True))

    def __init__(self):
        result = self.my_useful_static_function()
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
0

You need to use staticmethod like so:

class Foo: 
    @staticmethod 
    def my_method(): 
        print("This is a static method") 

    def my_other_method(self): 
        print("This is not static")

# This works
Foo.my_method()

# This won't work
Foo.my_other_method()

# This works though
foo_instance = Foo()
foo_instance.my_other_method()
Silvano Cerza
  • 954
  • 5
  • 16