|
1 | 1 | # coding=utf8 |
2 | | - |
| 2 | +from collections import OrderedDict |
3 | 3 | from django_echarts.utils.interfaces import merge_js_dependencies |
4 | 4 |
|
5 | 5 |
|
6 | 6 | class NamedCharts: |
7 | 7 | """ |
8 | | - A list containing multiple named charts. |
| 8 | + A data structure class containing multiple named charts. |
9 | 9 | """ |
10 | 10 |
|
11 | 11 | def __init__(self, page_title='EChart', **kwargs): |
12 | 12 | self.page_title = page_title |
13 | | - self._names = [] |
14 | | - self._charts = [] |
15 | | - |
16 | | - for name, chart in kwargs.items(): |
17 | | - self.add_chart(chart=chart, name=name) |
| 13 | + self._charts = OrderedDict() |
| 14 | + for k, v in kwargs.items(): |
| 15 | + self.add_chart(chart=v, name=k) |
18 | 16 |
|
19 | 17 | def add_chart(self, chart, name=None): |
20 | 18 | name = name or self._next_name() |
21 | | - self._names.append(name) |
22 | | - self._charts.append(chart) |
| 19 | + self._charts[name] = chart |
23 | 20 | return self |
24 | 21 |
|
| 22 | + def _next_name(self): |
| 23 | + return 'c{}'.format(len(self._charts)) |
| 24 | + |
| 25 | + # List-like feature |
| 26 | + |
25 | 27 | def __iter__(self): |
26 | | - for chart in self._charts: |
| 28 | + for chart in self._charts.values(): |
27 | 29 | yield chart |
28 | 30 |
|
29 | 31 | def __len__(self): |
30 | 32 | return len(self._charts) |
31 | 33 |
|
| 34 | + # Dict-like feature |
| 35 | + |
32 | 36 | def __contains__(self, item): |
33 | | - return item in self._names |
| 37 | + return item in self._charts |
34 | 38 |
|
35 | | - def __getattr__(self, item): |
36 | | - try: |
37 | | - i = self._names.index(item) |
38 | | - return self._charts[i] |
39 | | - except ValueError: |
40 | | - return super().__getattr__(item) |
| 39 | + def __getitem__(self, item): |
| 40 | + if isinstance(item, int): |
| 41 | + # c[1], Just compatible with Page |
| 42 | + return list(self._charts.values())[item] |
| 43 | + return self._charts[item] |
41 | 44 |
|
42 | | - def _next_name(self): |
43 | | - return 'c{}'.format(len(self._charts)) |
| 45 | + def __setitem__(self, key, value): |
| 46 | + self._charts[key] = value |
| 47 | + |
| 48 | + # Compatible |
| 49 | + |
| 50 | + def add(self, achart_or_charts): |
| 51 | + if not isinstance(achart_or_charts, (list, tuple, set)): |
| 52 | + achart_or_charts = achart_or_charts, # Make it a sequence |
| 53 | + for c in achart_or_charts: |
| 54 | + self.add_chart(chart=c) |
| 55 | + |
| 56 | + # Chart-like feature |
44 | 57 |
|
45 | 58 | @property |
46 | 59 | def js_dependencies(self): |
|
0 commit comments