Partial classes

Peter Otten __peter__ at web.de
Wed Jul 19 04:08:36 EDT 2006


Sanjay wrote:

> Hi All,
> 
> Not being able to figure out how are partial classes coded in Python.
> 
> Example: Suppose I have a code generator which generates part of a
> business class, where as the custome part is to be written by me. In
> ruby (or C#), I divide the code into two source files. Like this:
> 
> GeneratedPerson.rb
> Class Person
>   .
>   .
>   .
> 
> End Class
> 
> HandcraftedPerson.rb
> Class Person
>  .
>  .
>  .
> End Class
> 
> The intrepretor adds the code in both to compose the class Person.
> 
> What is the equivalent in Python? Inheriting is a way, but is not
> working in all scenerios.

I, like everybody else it seems, am interested to know why/when (multiple)
inheritance doesn't work. Meanwhile

# this is a hack
import inspect
import textwrap

class Generated:
    def generated(self):
        print "generated"

def class_body(Class):
    return textwrap.dedent(inspect.getsource(Class).split("\n", 1)[1])

class Handmade:
    exec class_body(Generated)
    def handmade(self):
        print "handmade"

if __name__ == "__main__":
    print dir(Handmade)
    Handmade().generated()

Peter



More information about the Python-list mailing list