x = 1
type(x)
int
type(int)
type
type(type)
type
int("2")
2
Point = type("Point", (object,), {"x": 0, "y": 0})
Point
__main__.Point
type(Point)
type
Point2 = type("Point2", (), {})
type(Point2)
type
Can we extend type?
class type2(type): pass
A = type2("A", (), {})
A
__main__.A
type(A)
__main__.type2
class B(object):
__metaclass__ = type2
B
__main__.B
type(B)
__main__.type2
# Can a metaclass be a string?
def fakemeta(name, bases, attrs):
return 1
class C(object):
__metaclass__ = fakemeta
C
1
mapping = []
class metapage(type):
def __init__(cls, name, bases, attrs):
type.__init__(cls, name, bases, attrs)
url = "/" + name
mapping.append((url, cls))
class page:
__metaclass__ = metapage
print mapping
class hello(page):
def get(self):
return "hello, world!"
print mapping
class bye(page):
def get(self):
return "goodbye!"
print mapping
[('/page', <class '__main__.page'>)] [('/page', <class '__main__.page'>), ('/hello', <class '__main__.hello'>)] [('/page', <class '__main__.page'>), ('/hello', <class '__main__.hello'>), ('/bye', <class '__main__.bye'>)]
# It is a common practice to base class construtor in the subclass
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Point3D(Point):
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
Most common use of metaclass is:
class Post(db.Model):
title = StringColumn()
timestamp = DateColumn()