Phil Hassey - game dev blog
Phil Hassey as Wolverine
"What kind of
arrogant jerk
has a website like this?"

Learning python by reinventing wheels …

I’ve learned a lot about python by implementing tinypy. Today I was thinking over my re-work of classes, objects, and inheritance in tinypy (not in trunk yet). I noted how in tinypy, I will be able to change the class of an object via a function call (a-la lua):

class A: pass
class B: pass
x = A() # x is an instance of A
setmeta(x,B) # x is now an instance of B !!!

So I thought to myself, I wonder if python can do that. Well, it can, and as per usual, its solution is quite elegant:

class A: pass
class B: pass
x = A() # x is an instance of A
x.__class__ = B # x is now an instance of B !!!

So, lesson of the day — you can dynamically change the class of an object in bigpy. Which, actually, I’ve sometimes wanted to do, I just didn’t realize I *could* do it.

3 Responses to “Learning python by reinventing wheels …”

  1. rgz Says:

    Indeed and let me tell you something i do. Often i have this class with methods that make very intensive data loading and sorting; and also methods to use that data, which naturally I write after the first ones.

    So it happens often that i while i’m in ipython, i want to edit the display methods and test them without reloading the data.

    I tried pickling the data but pickle complained about it for some reason, so my only option was to edit the methods in place and while ipython is great, i prefer my editor, besides i want to store the code in case it, you know, works.

    So i type reload Module then foo.__class__ = Module.Foo and voila! all the methods change but the instance variables remain the same so i don’t have to reload the data!!

  2. Alan Says:

    @ rgz:

    Now *that* is the best tip I’ve heard in ages

  3. Donny Viszneki Says:

    bigpy = CPython? You can’t do this in Jython or IronPython!