I have encountered a use-case where I have to define all the logic/rules in a static method to be called/utilized by a class method. And within the static method, it needs to access some static variables as thresholds for comparison. In my use case, the variable is a constant that is supposed to be hard coded and should not change or overwritten.
There are two ways to do this (global variable vs class variable) and I have written up a mock example showing both ways. My question is, is there any advantage/disadvantage for either method? More generally, when you need to define a static variable, what are the things to consider before you define it as global or class variables?
# method 1
var = 'hi'
class Test:
@staticmethod
def staticfn():
return var
def printstatic(self):
print(self.staticfn())
test = Test()
test.printstatic()
# method 2
class Test:
var = 'hi'
@staticmethod
def staticfn():
return Test.var
def printstatic(self):
print(self.staticfn())
test = Test()
test.printstatic()
Both methods can print string 'hi'
varisn'tglobal, it'slocalto the current module.