Created
May 22, 2012 14:59
-
-
Save alvesjnr/2769610 to your computer and use it in GitHub Desktop.
Simple example of metaclass usage in Python
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
" Python 2 version " | |
class MyMetaclass(type): | |
def __new__(cls, name, bases, dct): | |
attrs = ((name, value) for name, value in dct.items() if not name.startswith('__')) | |
attrs = dict(("__" + name.upper(), value) for name, value in attrs) | |
return super(MyMetaclass, cls).__new__(cls, name, bases, attrs) | |
class BaseClass(object): | |
__metaclass__ = MyMetaclass | |
class Banana(BaseClass): | |
v = 10 | |
if __name__ == '__main__': | |
kk = Banana() | |
try: | |
print "kk.v is: %s" % kk.v | |
except AttributeError: | |
print "There is not a 'kk.v' here" |
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
" Python 3 version " | |
class MyMetaclass(type): | |
def __new__(cls, name, bases, dct): | |
attrs = ((name, value) for name, value in dct.items() if not name.startswith('__')) | |
attrs = dict(("__" + name.upper(), value) for name, value in attrs) | |
return super(MyMetaclass, cls).__new__(cls, name, bases, attrs) | |
class BaseClass(object, metaclass=MyMetaclass): | |
pass | |
class Banana(BaseClass): | |
v = 10 | |
if __name__ == '__main__': | |
kk = Banana() | |
try: | |
print("kk.v is: ",kk.v) | |
except AttributeError: | |
print("There is not a 'kk.v' here") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment