I have a static class defined below that has two example of some default properties that I will be referencing in my code. This class will be much larger later on but I wanted a good way to keep all these values in one place, and access them in several areas of code.
'''
class Defaults:
Refractive: Tuple[float, float, float] = (0.5, 1.333, 5.0)
Temp: Tuple[int, int, int] = (10, 23, 40)
@staticmethod
def Min(property: Tuple[Any, Any, Any]) -> Any:
return property[0]
@staticmethod
def Max(property: Tuple[Any, Any, Any]) -> Any:
return property[2]
@staticmethod
def Default(property: Tuple[Any, Any, Any]) -> Any:
return property[1]
'''
Is there a way to access specific indices of these properties such as:
Defaults.Temp.Min()
Instead of this:
Defaults.Min(Defaults.Temp)
Or is there a better data structure to use here? Thanks.
I wouldn't use a class for this, and making this a method really doesn't make sense. Use another object instead of a static method:
from typing import NamedTuple, Generic, TypeVar
T = TypeVar("T", int, float)
# it doesn't have to be a namedtuple, either, you could just define a regular class
class MetaData(NamedTuple, Generic[T]): # or a better name
min: T
default: T
max: T
class Defaults:
Refractive: MetaData[float] = MetaData(0.5, 1.333, 5.0)
Temp: MetaData[int] = MetaData(10, 23, 40)
Then, you can just do:
print(Defaults.Temp.min)
Note, you should avoid Any
, it pretty much defeats the purpose of typing! It basically mean, "don't type check this". It serves as an "escape valve".
Note, Python isn't Java/C#... there really is no need for a "static class", indeed, taht isn't standard terminology. Normally, this would just be a regular module with global level "constants", eg
# in defaults.py
Refractive: MetaData[float] = MetaData(0.5, 1.333, 5.0)
Temp: MetaData[int] = MetaData(10, 23, 40)
I slightly modified @juanpa.arrivullaga's answer to the following below which works how I wanted. Wasn't sure about the error I was getting from their answer detailed in my comment on their answer, but the below solution works for me. Thanks to @juanpa.arrivillaga :)
class IntData(NamedTuple):
"""Tuple(Minimum, Default, Maximum) Int"""
Min: int
Default: int
Max: int
class FloatData(NamedTuple):
"""Tuple(Minimum, Default, Maximum) Float"""
Min: float
Default: float
Max: float
class ProtocolDefaults:
RI: FloatData = FloatData(0.5, 1.333, 5.0)
Temperature: IntData = IntData(10, 23, 40)
class SettingDefaults:
CT: FloatData = FloatData(20, 25, 30)
Access elements via:
ProtocolDefaults.Temperature.Min
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.