Kent Johnson wrote on 19.11.2005:

>Danny Yoo wrote:
>>Here's a small example that shows how classes can be treated just
>>like any other value in Python:
>> 
>> #########################################
>> def makeYa(superclass):
>>     class Ya(superclass):
>>         def sayHi(self):
>>             superclass.sayHi(self)
>>             print "ya"
>>     return Ya
>> 
>> class ValleyPerson:
>>     def sayHi(self):
>>         print "like, so, oh my gosh, hi?"
>> 
>> FrankensteinClass = makeYa(ValleyPerson)
>> instance = FrankensteinClass()
>> instance.sayHi()
>> #########################################
>
>Yeah, that'll work too :-) Or even
>
>def makeAB(moduleContainingSuperClass):
>  class A(moduleContainingSuperClass.A):
>    pass
>  class B(moduleContainingSuperClass.B)
>    pass
>  return A, B
>
>A, B = makeAB(siteA)
> 
>>So there's no need to do trickery with conditional imports; Python
>>treats classes as first-class objects that can be passed around.
>
>Trickery? ;) It's just using modules as first-class objects that are
>bound to names same as anything else. Which solution is better
>depends on whether you want to choose at the module level or with
>finer control.

Hm, sounds like there's more than one way to do it. ;-) Thanks a lot for your 
examples.

I hate to confess that I incorrectly described my requirements. It turns out 
that I am better off with a (variant of the) state design pattern. But I am 
stuck there, too.

The situation is this:

For every object, two string attributes are determined during initialization 
(one being read from a database, the other inherited as a superclass 
attribute). The first contains the site name, the second the object type. I'd 
like to set the template attribute to the proper class:

import Templates

self.site_name = 'SiteA'
self.template_type = 'Page'

self.template = ???

self.template should refer to Templates.SiteA.Page in this case (where SiteA is 
a module of package Templates, and Page is a class within that module). Danny 
already said that classes can be treated just like any other object - but how 
do I get from a string to a class or module name?

Thanks for all your help, and sorry for my ignorance,

Jan
-- 
Any sufficiently advanced technology is indistinguishable from a Perl script. - 
Programming Perl
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to