ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-tutor
python-tutor
Re: [Tutor] Re-instantiate within __init__
by Danny Yoo other posts by this author
Apr 19 2006 11:29AM messages near this date
[Tutor] Re-instantiate within __init__ | Re: [Tutor] Re-instantiate within __init__
>  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.
_______________________________________________
Tutor maillist  -  Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Jan Eden
Danny Yoo
Kent Johnson
Alan Gauld

Privacy Policy | Email Opt-out | Feedback | Syndication
© 2004 ActiveState, a division of Sophos All rights reserved