renumbering chapters >= 19
This commit is contained in:
22
24-class-metaprog/autoconst/autoconst.py
Normal file
22
24-class-metaprog/autoconst/autoconst.py
Normal file
@@ -0,0 +1,22 @@
|
||||
# tag::WilyDict[]
|
||||
class WilyDict(dict):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.__next_value = 0
|
||||
|
||||
def __missing__(self, key):
|
||||
if key.startswith('__') and key.endswith('__'):
|
||||
raise KeyError(key)
|
||||
self[key] = value = self.__next_value
|
||||
self.__next_value += 1
|
||||
return value
|
||||
# end::WilyDict[]
|
||||
|
||||
# tag::AUTOCONST[]
|
||||
class AutoConstMeta(type):
|
||||
def __prepare__(name, bases, **kwargs):
|
||||
return WilyDict()
|
||||
|
||||
class AutoConst(metaclass=AutoConstMeta):
|
||||
pass
|
||||
# end::AUTOCONST[]
|
||||
55
24-class-metaprog/autoconst/autoconst_demo.py
Executable file
55
24-class-metaprog/autoconst/autoconst_demo.py
Executable file
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
"""
|
||||
Testing ``WilyDict``::
|
||||
|
||||
>>> from autoconst import WilyDict
|
||||
>>> wd = WilyDict()
|
||||
>>> len(wd)
|
||||
0
|
||||
>>> wd['first']
|
||||
0
|
||||
>>> wd
|
||||
{'first': 0}
|
||||
>>> wd['second']
|
||||
1
|
||||
>>> wd['third']
|
||||
2
|
||||
>>> len(wd)
|
||||
3
|
||||
>>> wd
|
||||
{'first': 0, 'second': 1, 'third': 2}
|
||||
>>> wd['__magic__']
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
KeyError: '__magic__'
|
||||
|
||||
Testing ``AutoConst``::
|
||||
|
||||
>>> from autoconst import AutoConst
|
||||
|
||||
# tag::AUTOCONST[]
|
||||
>>> class Flavor(AutoConst):
|
||||
... banana
|
||||
... coconut
|
||||
... vanilla
|
||||
...
|
||||
>>> Flavor.vanilla
|
||||
2
|
||||
>>> Flavor.banana, Flavor.coconut
|
||||
(0, 1)
|
||||
|
||||
# end::AUTOCONST[]
|
||||
|
||||
"""
|
||||
|
||||
from autoconst import AutoConst
|
||||
|
||||
|
||||
class Flavor(AutoConst):
|
||||
banana
|
||||
coconut
|
||||
vanilla
|
||||
|
||||
|
||||
print('Flavor.vanilla ==', Flavor.vanilla)
|
||||
Reference in New Issue
Block a user