[Tutor] Re-instantiate within __init__

Kent Johnson kent37 at tds.net
Wed Apr 19 17:32:59 CEST 2006

Jan Eden wrote:
> Hi,
> is it correct that an object cannot be re-instantiated within it's __init__ method?
> I tried:
> class Omega:
>     def Display(self):
>         print self
> class Alpha(Omega):
>     def __init__(self):
>         self = Beta()
> class Beta(Omega):
>     def __init__(self):
>         pass
> objectus = Alpha()
> objectus.Display()
> which prints
> <__main__.Alpha instance at 0x54d50>

Binding to self in a method just changes the local value of self, it 
doesn't change the object itself. The only thing special about 'self' is 
the way it is bound before the method is entered; inside the method it 
is a local name like any other.

To bind objectus to a new object you have to assign to objectus. But I 
suspect you are really looking for a way to change the behaviour of the 
object bound to objectus.
> Background: I need to create a new object upon instantiation when a
database query returns no records. The rest of the program should just
use the new object.
> Is there any way to achieve this? I can always place the equivalent
> of
'self = Beta()' in the Display() function:
>     def Display(self):
>         if self.not_found:
>             self = Beta()
>             self.Display()
>             return
>         print self
>  but this does not look very elegant.

I don't understand what you are trying to do, but here are some ideas:
- have Display() look at self.not_found itself, or pass self.not_found 
as a parameter to display.
- use a factory method to create a class of the correct type
- change self.Display to be the correct function
- you can change the class of an object at runtime by assigning to its 
__class__ attribute. This may be what you are looking for but I suspect 
there is a simpler, less magic solution
- I'm not sure why classes are needed at all here.

Can you give a more complete example of what you are trying to do? Even 
if your code above worked the way you want it to, it wouldn't do 
anything interesting, since Alpha and Beta have exactly the same 
attributes and behaviour.


More information about the Tutor mailing list