Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cb109/6122d08efc2b76d52f3fc011bdeffdc9 to your computer and use it in GitHub Desktop.
Save cb109/6122d08efc2b76d52f3fc011bdeffdc9 to your computer and use it in GitHub Desktop.
Give class attributes knowledge about how they are used on their parent class
class Bar:
def __init__(self):
self.parent_class_attr_name = None
class LetClassAttributesKnowTheirName(type):
def __new__(mcs, name, bases, attributes):
for attr_name, attr_value in attributes.items():
if isinstance(attr_value, Bar):
attr_value.parent_class_attr_name = attr_name
return super().__new__(mcs, name, bases, attributes)
class Foo(metaclass=LetClassAttributesKnowTheirName):
bar1 = Bar()
bar2 = Bar()
foo = Foo()
print(foo.bar1.parent_class_attr_name)
print(foo.bar2.parent_class_attr_name)
# >>> 'bar1'
# >>> 'bar2'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment