I want to understand in my case if I should use static or class method. The idea: I'm not editing any class variable, but I'm using this variable.
example 1:
class RandClass():
static_variable = "some rand value to static variable"
@classmethod
def func_that_return_string_contain_static_variable(cls):
return "some rand string" cls.static_variable
example2:
class RandClass():
static_variable = "some rand value to static variable"
@staticmethod
def func_that_return_string_contain_static_variable():
return "some rand string" RandClass.static_variable
What is the best practice?
CodePudding user response:
The best practice is most likely using example1
, or an @classmethod
.
In general, class methods are used when methods are specific to a class (and therefore use values from the class) without needing instantiation (and therefore a self
parameter).
Static methods are generally used simply to group methods structurally - not to access attributes of the class they're in (and use them in any way).
The cls
parameter when using an @classmethod
will be a reference to the class it was called on, or simply RandClass
when called as RandClass.func_that_return_string_contain_static_variable()
. Therefore, both code blocks do the exact same thing - it's simply that using an @classmethod
is preferred for this purpose, and using an @staticmethod
is more of a workaround.
Hope this helps!
CodePudding user response:
Its a question of inheritance in subclasses. Suppose I create class Rand2(RandClass):
. Should it be able to override the class variable? In the classmethod
case, methods on the parent class will use the variable on the subclass (if redefined in the subclass), not the parent. This is polymorphism at work - I can change what a base method does by changing a variable on the class.
class RandClass():
static_variable = "some rand value to static variable"
@classmethod
def func_that_return_string_contain_static_variable(cls):
return "some rand string" cls.static_variable
class Rand2(RandClass):
static_variable = "and now for something completely different"
print(RandClass().func_that_return_string_contain_static_variable())
print(Rand2().func_that_return_string_contain_static_variable())
Outputs
some rand stringsome rand value to static variable
some rand stringand now for something completely different
In the staticmethod
case, the parent variable is used regardless of what the subclass tries to do.
if its important that a method always use the variable defined on the base class, then use example 2. The other 99% of the time, if you use variables on the class, use a class method and access it via cls
.