Created
July 22, 2022 00:37
-
-
Save pingzh/2fcb3cc71acbfaf4222e0225d6f63202 to your computer and use it in GitHub Desktop.
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
def protect(*protected): | |
"""Returns a metaclass that protects all attributes given as strings""" | |
class Protect(type): | |
has_base = False | |
def __new__(meta, name, bases, attrs): | |
if meta.has_base: | |
for attribute in attrs: | |
if attribute in protected: | |
raise AttributeError('Overriding of attribute "%s" not allowed.'%attribute) | |
meta.has_base = True | |
klass = super().__new__(meta, name, bases, attrs) | |
return klass | |
return Protect | |
class Parent(metaclass=protect("do_something", "do_something_else")): | |
def do_something(self): | |
'''This is where some seriously important stuff goes on''' | |
pass | |
class Child(Parent): | |
def do_something(self): | |
'''This will raise an error during class creation.''' | |
pass | |
c = Child() | |
c.do_something() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment