Create a class at run-time
Steve Holden
steve at holdenweb.com
Fri Mar 26 15:19:44 EDT 2010
Michel wrote:
> Thanks Peter.
>
> I searched a little bit more and wrote the following example:
>
> ------------------------------------
> import types
>
> class MyClass:
>
> def test_toto(self):
> print type(self)
> print self.name
>
> def test_toto(self):
> print type(self)
> print self.name
>
> MyDynClass = types.ClassType("MyDynClass", (object, ), {})
> MyDynClass.__module__ = "test.complex.hierarchy"
> MyDynClass.test_toto = test_toto
>
> t1 = MyDynClass()
> t2 = MyDynClass()
>
> t1.name = "Marcel"
> t2.name = "Oscar"
>
> t1.test_toto()
> t2.test_toto()
>
> c1 = MyClass()
> c1.name = "Raoul"
> c1.test_toto()
> --------------------------------
>
> the output is:
>
> <class 'test.complex.hierarchy.MyDynClass'>
> Marcel
> <class 'test.complex.hierarchy.MyDynClass'>
> Oscar
> <type 'instance'>
> Raoul
>
> I'm wondering why the type of the self parameter is not 'instance' in
> the calls
> t1.test_toto() and t2.test_toto()
>
> The rest of the behavior is correct though, so I guess it's just
> internal Python stuff.
>
Yes, it's just that MyClass is an old-style class (its type is <type
'classobj'>) whereas MyDynClass is a new-style class (its type is <type
'type'>, because it inherits from object).
It's as though you had written
class MyClass:
...
class MyDynClass(object):
...
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list