Created
December 7, 2020 21:33
-
-
Save alkasm/a8de21e4e2fb9034c98657634280b933 to your computer and use it in GitHub Desktop.
Metaclass to add class attrs
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 Meta1(type): | |
@classmethod | |
def __prepare__(cls, *args): | |
return {"decorator": lambda f: f, "prepared_attr": "prepared_attr_value"} | |
class Meta2(type): | |
def __new__(cls, name, bases, namespace): | |
namespace["decorator"] = lambda f: f | |
namespace["new_attr"] = "new_attr_value" | |
return super().__new__(cls, name, bases, namespace) | |
class Test1(metaclass=Meta1): | |
prep = prepared_attr | |
@decorator | |
def f(self): | |
print(self.__class__.prepared_attr) | |
class Test2(metaclass=Meta2): | |
prep = new_attr | |
@decorator | |
def f(self): | |
print(self.__class__.new_attr) | |
t1 = Test1() | |
t1.f() | |
t2 = Test2() # NameError: name 'new_attr' is not defined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment