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(P erson)):
.... 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_e xtend
# 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.__nam e__, name))
# module is added automatically
module = dict.pop('__mod ule__', None)
if module is not None:
modules = getattr(extende d, '__modules__', None)
if modules is None:
modules = extended.__modu les__ = [extended.__modu le__]
modules.append( module)
# replace the docstring only if it is not None
doc = dict.pop('__doc __', None)
if doc is not None:
setattr(extende d, '__doc__', doc)
# now patch the original class with all the new attributes
for attrname, value in dict.items():
setattr(extende d, attrname, value)
return extended
Ziga