Skip to content

Instantly share code, notes, and snippets.

@gloryofrobots
Created February 6, 2014 20:16
Show Gist options
  • Save gloryofrobots/8851750 to your computer and use it in GitHub Desktop.
Save gloryofrobots/8851750 to your computer and use it in GitHub Desktop.
Python metaclass example
class QueryBook(object):
def __init__(self, tableName):
self.tableName = tableName
def add(self, queryName, query):
#setattr(self, queryName, query)
def execute(*args):
self.__execute(query, args)
setattr(self, "exec"+queryName.upper(), execute)
def __execute(self, query, *args):
print self.tableName,query,args
class MetaObjectQueryBook(type):
def __new__(mcs, name, bases, dct):
tableName = dct["TABLE_NAME"]
book = QueryBook(tableName)
del dct["TABLE_NAME"]
attributes = ((name, value) for name, value in dct.items() if not name.startswith('__'))
for name, value in attributes:
book.add(name, value)
return super(MetaObjectQueryBook, mcs).__new__(mcs, name, bases, {"queryBook":book})
class One:
__metaclass__ = MetaObjectQueryBook
TABLE_NAME = "login"
CREATE = "CREATE TABLE LOGIN"
INSERT = "CREATE TABLE DATA"
one = One()
one.queryBook.execCREATE(1,2,3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment