define class over 2 files

Jan Kaliszewski zuo at chopin.edu.pl
Tue Aug 18 22:42:46 CEST 2009


18-08-2009 o 06:58:58 Xavier Ho <contact at xavierho.com> wrote:

> On Tue, Aug 18, 2009 at 2:45 PM, naveen <naveen.garg at gmail.com> wrote:
>
>> Is it possible to split up a class definition over multiple files?
>> -
> Answer in short, I don't think so.

Why not?

---------
File a.py:

  class MyClass:
      def foo(self, x):
          return x * 6

---------
File b.py:

  import a
  def bar(self):
      print 'bar'
  def baz(self, a):
      print self.foooo(a)

  # adding methods by hand:
  a.MyClass.bar = bar
  a.MyClass.baz = baz

---------
File c.py

  import a
  def foooo(self, a):
      return a * self.foo(4)
  def baaar(self):
      print self.baz('tralala')
  def bazzz(self):
      print 'bzzzzzzzzzz'

  # adding methods more automaticly:
  for name, obj in globals().values():
      setattr(a.MyClass, name, obj)


>  Now why would you want to do that?

It's a good question. As others said it's very probable that some other
solution would be better (e.g. inheritance).

Cheers,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list