假设我有一个class
,它需要一个函数(或者应该说方法),它是:
- 独立于我的
class
个实例——不需要self
个参数; - 仅在我的
class
对象内调用 - I won't need access to it at any point (to override it f或 example);
我应该(A)将其放置在class
中并将其标记为@staticmethod
,还是(B)将其定义在class
对象之外(但在同一名称空间中)?为什么?
例子:
class A:
def __init__(self, my_int):
self.my_int = my_int
def my_int_and_4(self):
print(self.adder(self.my_int,4))
@staticmethod
def adder(a,b):
return a+b
或
def adder(a,b):
return a+b
class B:
def __init__(self, my_int):
self.my_int = my_int
def my_int_and_4(self):
print(adder(self.my_int,4))
编辑:也许这个例子有点过于简单.我应该补充一点,我的版本"adder
"专门用于我的class
,没有其他情况.