Created
March 30, 2017 19:59
-
-
Save brake/4e45593c63c80e21c876f95fb120222a to your computer and use it in GitHub Desktop.
Metaclass for attributes of specific type sets the attribute b to attribute name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Meta(type): | |
| def __new__(cls, name, bases, attrs): | |
| for n, v in attrs.viewitems(): | |
| if isinstance(v, E): | |
| v.b = n | |
| return super(Meta, cls).__new__(cls, name, bases, attrs) | |
| class E(object): | |
| def __init__(self, a): | |
| self.a = a | |
| self.b = None | |
| def __repr__(self): | |
| return '{0.__class__.__name__}({0.a}, {0.b})'.format(self) | |
| class C(object): | |
| __metaclass__ = Meta | |
| Aaa = E('1') | |
| Bbb = E('2') | |
| # for attr, val in C.__dict__.items(): | |
| # if isinstance(val, E): | |
| # val.b = attr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment