calling subclass constructor question

I

In Han Kang

Hello everyone and thank you for being such a good community.

Anyway, I was wondering...I have an super class which is the superclass
for 5 other classes. However, I want to be able to call the subclass
constructors from the super class. Is this possible?

Thank you in advance
 
D

Diez B. Roggisch

In said:
Hello everyone and thank you for being such a good community.

Anyway, I was wondering...I have an super class which is the superclass
for 5 other classes. However, I want to be able to call the subclass
constructors from the super class. Is this possible?

If you have a subclass, it's constructor is called - so why do you want
to call it again ? It smells after bad design here - you might consider
providing more dtail on the problem you want to solve by this, thus we
might be able to suggest a more viable solution (or actually, a solution
at all...)


Diez
 
W

wittempj

No. You will go into an infinite loop - at least I get there when I try
someting like this:

class Base:
def __init__(self):
Derived.__init__(self)
print 'Base'

class Derived(Base):
def __init__(self):
Base.__init__(self)
print 'Derived'

d = Derived()
 
S

Steven Bethard

In said:
Anyway, I was wondering...I have an super class which is the superclass
for 5 other classes. However, I want to be able to call the subclass
constructors from the super class. Is this possible?

Are you trying to use your superclass as a factory?

If so, one option is something like:

py> class A(object):
.... @staticmethod
.... def subclass(i):
.... return A.__subclasses__()()
....
py> class B(A):
.... pass
....
py> class C(A):
.... pass
....
py> A()
<__main__.A object at 0x011861B0>
py> A.subclass(0)
<__main__.B object at 0x01186070>
py> A.subclass(1)
<__main__.C object at 0x011861B0>

I've never used this strategy, but I know that others have. You can
probably search the list for __subclasses__ and find some more information.

STeVe
 

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

Forum statistics

Threads
474,252
Messages
2,571,267
Members
47,908
Latest member
MagdalenaR

Latest Threads

Top