HWende
HWende

Reputation: 1705

Can inherited class change type of elements in base class

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

Upvotes: 1

Views: 67

Answers (1)

Steef
Steef

Reputation: 34665

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

Upvotes: 4

Related Questions