Mixing classes...

I

Ivan Voras

Is this possible:

class C1:
def somemethods(self):
"""methods do stuff, create member variables"""
pass

def f1():
"""function returns instances of C1, somewhat manipulated into specific
states"""
return C1()


class C2(C1): # C2 derives from C1
def othermethods(self):
"""new methods are introduced, but no new member variables (they work
on existing ones)"""
pass



# So far, everything's ok. Now, i want to create instance of
# C1 using f1:

c = f1() # could be equal to "c=C1()", but not always...

# ... and somehow "add" or "overlay" the additional methods
# declared in C2 on the object "c". I tried this:

c.othermethods=C2.othermethods

c.othermethods() # fails here, is confused about what is 'self'


#######
While this is probably considered "strange", and it's certainly not good
design style, I somehow feel it could be possible to do in python. Any
clues?
 
H

Hans Nowak

Ivan said:
Is this possible:

class C1:
def somemethods(self):
"""methods do stuff, create member variables"""
pass

def f1():
"""function returns instances of C1, somewhat manipulated into
specific states"""
return C1()


class C2(C1): # C2 derives from C1
def othermethods(self):
"""new methods are introduced, but no new member variables (they
work on existing ones)"""
pass



# So far, everything's ok. Now, i want to create instance of
# C1 using f1:

c = f1() # could be equal to "c=C1()", but not always...

# ... and somehow "add" or "overlay" the additional methods
# declared in C2 on the object "c". I tried this:

c.othermethods=C2.othermethods

c.othermethods() # fails here, is confused about what is 'self'


#######
While this is probably considered "strange", and it's certainly not good
design style, I somehow feel it could be possible to do in python. Any
clues?

Use new.instancemethod:
.... def somemethods(self):
.... print 'somemethods'
........ return C1()
........ def othermethods(self):
.... print 'othermethods'
....othermethods

HTH,
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top