Can inherited class change type of elements in base class

Go To StackoverFlow.com

1

Assume I have classes A1 and A2 and a class B that has elements of type A1/A2.

Now I have a class B'(B) (it inherits from B). Can this class use A1' and A2' instead of A1 and A2, can this new class somehow exchange the type of elements in the base class?

Normally I would say it's impossible, but since this is about python... :P

2012-04-04 06:57
by HWende
Does "elements" mean "attributes" here or something else - John La Rooy 2012-04-04 07:09
What you describe sounds like standard polymorphism and with correct type-declarations (always declaring a supertype as reference-type) would well be possible in other languages as well, as long as A1' and A2' inherit from A1 and A2 - BergmannF 2012-04-04 07:12
@gnibbler yes it doe - HWende 2012-04-04 07:21
If I need the baseclass (of B') to use A1' instead of A1, I don't see how that would be possible in C++ since I can not overwrite the baseclass elements with my own like in phyton... (maybe I'm wrong - HWende 2012-04-04 07:23
It's trivial in Python, because Python is fully dynamic. In C++ terms you can (very loosely :-) ) think of it as "everything is always virtual" - torek 2012-04-04 08:39


4

You mean like this?

class A1(object):
    pass

class A1Child(A1):
    pass

class A2(object):
    pass

class A2Child(A2):
    pass


class B(object):

    a1_instance = None
    a2_instance = None

    def __init__(self):
        self.a1_instance = A1()
        self.a2_instance = A2()

class BChild(B):

    def __init__(self):
        self.a1_instance = A1Child()
        self.a2_instance = A2Child()


b_instance = B()

print b_instance.a1_instance
print b_instance.a2_instance


bchild_instance = BChild()

print bchild_instance.a1_instance
print bchild_instance.a2_instance
2012-04-04 07:04
by Steef
Excellent! Thanks for the example code and I AM impressed by python. Again - HWende 2012-04-04 07:18
Ads