Skip to main content

Python: Fun with Classes

#!/usr/bin/python

#
# Author: Shannon -jj Behrens
# Date: Fri Mar 3 16:43:43 PST 2006
#
# In response to: http://secretartofscience.com/blog/?p=8
#
# Although Python isn't a prototype-based language, it's possible to do a lot
# of these same wacky ideas in Python.
#
# By the way, Io is a cool, new prototype based language. I've blogged about
# it before. There was also a knockoff of Python that was prototype based, but
# I don't remember the name--email me if you must know.
#


# Ok, let's start by changing our class on the fly.

class Draws(object):

def draw(self):
print "draw"


class DrawsSmall(Draws):

def draw(self):
print "small:",
Draws.draw(self)


obj = Draws()
obj.draw()
obj.__class__ = DrawsSmall
obj.draw()
print


# This time, let's mixin something on the fly.

class DrawsBig(Draws):

def draw(self):
print "big:",
Draws.draw(self)


obj = Draws()
obj.draw()
class MixedIn(DrawsBig, Draws): pass
obj.__class__ = MixedIn
obj.draw()
print


# This time, do it dynamically. I'll leave it as an exercise to the reader to
# implement "replace_parent_class".

import random

def inject_parent_class(obj, Class):
NewClass = type("DynamicGeneratedClass",
(Class,) + obj.__class__.__bases__, {})
obj.__class__ = NewClass


obj = Draws()
obj.draw()
Class = random.choice([DrawsBig, DrawsSmall])
inject_parent_class(obj, Class)
obj.draw()

Comments

Anonymous said…
It was called Prothon. And it's apparently as dead as a Norwegian Blue parrot.