Skip to content

Instantly share code, notes, and snippets.

@brake
Created March 30, 2017 19:59
Show Gist options
  • Select an option

  • Save brake/4e45593c63c80e21c876f95fb120222a to your computer and use it in GitHub Desktop.

Select an option

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
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