[Tutor] Dynamic inheritance?

Kent Johnson kent37 at tds.net
Sun Nov 20 03:46:37 CET 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.

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



More information about the Tutor mailing list