is it possible to dividing up a class in multiple files?
Ziga Seilnacht
ziga.seilnacht at gmail.com
Mon Aug 7 10:15:46 EDT 2006
Martin Höfling wrote:
> Hi there,
>
> is it possible to put the methods of a class in different files? I just
> want to order them and try to keep the files small.
>
> Regards
> Martin
You could use something like this:
"""
Example usage:
>>> class Person(object):
... def __init__(self, first, last):
... self.first = first
... self.last = last
...
>>> john = Person('John', 'Smith')
>>> jane = Person('Jane', 'Smith')
>>> class Person(extend(Person)):
... def fullname(self):
... return self.first + ' ' + self.last
...
>>> john.fullname()
'John Smith'
>>> jane.fullname()
'Jane Smith'
"""
def extend(cls):
extender = object.__new__(Extender)
extender.class_to_extend = cls
return extender
class Extender(object):
def __new__(cls, name, bases, dict):
# check that there is only one base
base, = bases
extended = base.class_to_extend
# names have to be equal otherwise name mangling wouldn't work
if name != extended.__name__:
msg = "class names are not identical: expected %r, got %r"
raise ValueError(msg % (extended.__name__, name))
# module is added automatically
module = dict.pop('__module__', None)
if module is not None:
modules = getattr(extended, '__modules__', None)
if modules is None:
modules = extended.__modules__ = [extended.__module__]
modules.append(module)
# replace the docstring only if it is not None
doc = dict.pop('__doc__', None)
if doc is not None:
setattr(extended, '__doc__', doc)
# now patch the original class with all the new attributes
for attrname, value in dict.items():
setattr(extended, attrname, value)
return extended
Ziga
More information about the Python-list
mailing list