[Tutor] Re-instantiate within __init__

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Apr 19 20:30:05 CEST 2006


> 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>
>
> 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.

I think you're looking for the "Strategy" design pattern: your class has a 
default behavior, but in a certain case, you want it to switch behaviors 
to something else.

http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/StrategyPattern.htm

That is, rather than Alpha being a subclass of Omega, Alpha can have an 
instance of Omega:

#########################################
class Alpha:
     def __init__(self):
         self.strategy = DefaultStrategy()

     def display(self):
         self.strategy.display()


class DefaultStrategy:
     def display(self):
         print "I am the default strategy"
#########################################

The advantage here is that the strategy can be swapped out just by setting 
self.strategy to something else.


More information about the Tutor mailing list