[Tutor] Transforming object into subclass instance

2005-10-30 Thread Jan Eden
Hi,

my program uses an initial switch statement to create an object:

valid_types = dict(
pages=Show.Page,
syndicated=Show.Syndicated,
authors=Show.Author,
author_list=Show.AuthorList,
galleries=Show.Gallery,
pictures=Show.Picture,
slideshow=Show.SlidePicture,
tex=Show.Tex,
blogs=Show.Blog,
blogentries=Show.BlogEntry,
search=Show.Search,
search_author=Show.SearchAuthor,
not_found=Show.NotFound
)
# ... code ommitted...

page = valid_types[type]]()

For a certain class, it is only during the execution of the __ini__ method that 
I can distinguish between two subtypes (subclasses). The subclasses define two 
different versions of method A.

Now my question is: How can I turn an object of class X into an object of 
either class Y or Z while (retaining all the attributes defined so far).

I know I could solve the problem by using another switch statement - but is 
there consistent OOP solution for this problem?

Thanks,

Jan
-- 
Hanlon's Razor: Never attribute to malice that which can be adequately 
explained by stupidity.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Transforming object into subclass instance

2005-10-30 Thread Kent Johnson
Jan Eden wrote:
 Now my question is: How can I turn an object of class X into an
 object of either class Y or Z while (retaining all the attributes
 defined so far).

This is easy, in fact - you can change the class of an instance by assigning to 
its __class__ attribute:
  class F(object):
 ...   def p(self): print F
 ...
  class G(object):
 ...   def p(self): print G
 ...
  f=F()
  f.p()
F
  type(f)
class '__main__.F'
  f.__class__ = G
  f.p()
G
  type(f)
class '__main__.G'
 
 I know I could solve the problem by using another switch statement -
 but is there consistent OOP solution for this problem?

I'm not sure I would call this solution OO or pretty but it does work.

Kent
-- 
http://www.kentsjohnson.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor