在我的课堂上,我想调用一个非成员函数,其引用存储在成员变量中。我的问题是它试图将self
传递给函数作为第一个参数。如何避免这种情况?
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()
答案 0 :(得分:2)
使用staticmethod
:
class MyClass:
my_useful_static_function = staticmethod(crcmod.mkCrcFun(0x11021, True))
def __init__(self):
result = self.my_useful_static_function()
答案 1 :(得分:0)
您需要像这样使用staticmethod:
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()