Created
April 5, 2024 08:41
-
-
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
This file contains 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 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