Issue
I have an Enum class Station. (I'm using aenum, a library that "extends" python enum, and allows to use enums that have both an integer and a string) This class Station) stores constants, with number and string representation. All fine.
Now, I want to store constant lists of Station objects. What I'm doing works but feels wrong. (I'm kind of new to python / programing.) Does someone have an advice on that ? thank you.
Here is my code :
from typing import List
from aenum import Enum
from abc import ABC
class Station(Enum):
_init_ = 'value string'
BASTILLE = 3, 'Bastille'
LEDRU = 1, 'Ledru Rollin'
REPU = 10, 'République'
CHATELET = 2, 'Châtelet les Halles'
OURCQ = 5, 'Ourcq'
def __str__(self):
return self.string
@property
def nb(self):
return self.value
class StationEnsemble(ABC):
name :str
stations : List[Station]
@property
def station_nbs_list(self):
return [st.nb for st in self.stations]
class RecentStations(StationEnsemble):
stations = [Station.OURCQ,Station.LEDRU,Station.CHATELET]
class EastStations(StationEnsemble):
stations=[Station.BASTILLE,Station.OURCQ,Station.CHATELET]
Solution
Using several classes for your lists seems awkward. Why not just write a single class and make the specific lists its instances? This would make the property
work (since it needs to be looked up on an instance) also give you a chance to fill in the name
attribute you type hinted but never initialized.
class StationEnsemble:
def __init__(self, name: str, stations: List[Station]):
self.name = name
self.stations = stations
@property
def station_nbs_list(self):
return [st.nb for st in self.stations]
RecentStations = StationsEnsemble("recent", [Station.OURCQ, Station.LEDRU, Station.CHATELET])
EastStations = StationsEnsemble("east", [Station.BASTILLE, Station.OURCQ, Station.CHATELET])
Answered By - Blckknght
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.