The following code includes several different ways of declaring a static variable used by a class. Are there any functional differences between them? Are there any advantages/disadvantages for each one? Is there a better way that I don't know about?
# 1st way
class ApplePie:
type = "apple"
def __init__(self):
print(f"I'm an {ApplePie.type} pie!")
# 2nd way
class ApplePie:
@property
def type(self) -> str:
return "apple"
def __init__(self):
print(f"I'm an {self.type} pie!")
# 3rd way
from functools import cached_property
class ApplePie:
@cached_property
def type(self) -> str:
return "apple"
def __init__(self):
print(f"I'm an {self.type} pie!")
Which method would you guys use and why?
Your first example doesn't work. You can define a static variable like this:
class ApplePie:
type = "apple"
def __init__(self):
print(f"I'm an {ApplePie.type} pie!")
This is a class property (i.e. it's shared among all instances of this class), as opposed to an instance property, accessed through self
, like in your second example. These can differ among multiple instances of a class.
Your third example is
Useful for expensive computed properties of instances that are otherwise effectively immutable.
as described in the official documentation.