Код: Выделить всё
class Statistic:
def __init__(self, stat_id: str):
self.stat_id: str = stat_id
def __repr__(self):
return f"({self.stat_id})"
class StatisticDict(dict[str, Statistic]):
def __init__(self):
super().__init__()
def register_statistic(self, statistic: Statistic):
if statistic.stat_id not in self:
self[statistic.stat_id] = statistic
class Entity:
def __init__(self, name: str):
self.name = name
self.stats: StatisticDict = StatisticDict()
def register_statistic(self, statistic: Statistic):
self.stats.register_statistic(statistic)
def test_scoping_1():
stat1 = Statistic("stat1")
my_entity = Entity("entity1")
my_entity.register_statistic(stat1)
def test_scoping_2():
stat2 = Statistic("stat2")
my_entity = Entity("entity2")
my_entity.register_statistic(stat2)
print(f"Entity Stats: {my_entity.stats}")
if __name__ == "__main__":
test_scoping_1()
test_scoping_2()
Код: Выделить всё
Entity Stats: {'stat2': (stat2)}
Код: Выделить всё
class Statistic:
def __init__(self, stat_id: str):
self.stat_id: str = stat_id
def __repr__(self):
return f"({self.stat_id})"
class StatisticDict(dict[str, Statistic]):
def __init__(self):
super().__init__()
def register_statistic(self, statistic: Statistic):
if statistic.stat_id not in self:
self[statistic.stat_id] = statistic
class Entity:
def __init__(self, name: str, stats: StatisticDict = StatisticDict()):
self.name = name
self.stats: StatisticDict = stats
def register_statistic(self, statistic: Statistic):
self.stats.register_statistic(statistic)
def test_scoping_1():
stat1 = Statistic("stat1")
my_entity = Entity("entity1")
my_entity.register_statistic(stat1)
def test_scoping_2():
stat2 = Statistic("stat2")
my_entity = Entity("entity2")
my_entity.register_statistic(stat2)
print(f"Entity Stats: {my_entity.stats}")
if __name__ == "__main__":
test_scoping_1()
test_scoping_2()
Код: Выделить всё
{'stat1': (stat1), 'stat2': (stat2)}
Код: Выделить всё
def __init__(self, name: str, stats: StatisticDict = StatisticDict()):
Код: Выделить всё
self.stats: StatisticDict = stats
Подробнее здесь: https://stackoverflow.com/questions/798 ... ing-issues
Мобильная версия