define class over 2 files

S

Steven D'Aprano

Is it possible to split up a class definition over multiple files?

Not exactly, but you can do variations of this:


In file A.py, create:

class Parent:
def method(self):
return "Method"


In file B.py, do this:

import A
class Child(B.parent):
def another_method(self):
return "Another Method"


Now your class Child has two methods, method() and another_method().


Similarly, you can do this:

# File A.py

def function(x, y):
return x+y # or something more complicated


# File B.py

import A

def MyClass(object):
def func(self, x, y):
return A.function(x, y)
 
N

naveen

Is it possible to split up a class definition over multiple files?
Not exactly, but you can do variations of this: .... [subclass a class]
Steven

Thanks Steven.
I guess I will just preprocess the script:
<class.sh>
cat partA.py > class.py
cat partB >> class.py
python class.py
</class.sh>
 
S

Simon Forman

Not exactly, but you can do variations of this:


In file A.py, create:

class Parent:
   def method(self):
       return "Method"


In file B.py, do this:

import A
class Child(B.parent):

class Child(A.Parent):
 
J

Jan Kaliszewski

18-08-2009 o 06:58:58 Xavier Ho said:
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
 
G

greg

naveen said:
Not exactly, but you can do variations of this:

... [subclass a class]

Multiple inheritance can also be useful:

# A_Part1.py

class A_Part1:
...

# A_Part2.py

class A_Part2:
...

# A.py

from A_Part1 import A_Part1
from A_Part2 import A_Part2

class A(A_Part1, A_Part2):
...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,149
Latest member
Vinay Kumar Nevatia0
Top