Skip to content Skip to sidebar Skip to footer

How To Convert (inherit) Parent To Child Class?

I would like to know how to convert parent object that was return by some function to child class. class A(object): def __init__(): pass class B(A): def functionIn

Solution 1:

Python does not support "casting". You will need to write B.__init__() so that it can take an A and initialize itself appropriately.

Solution 2:

I have a strong suspicion, nay, conviction, that there is something horribly wrong with your program design that it requires you to do this. In Python, unlike Java, very few problems require classes to solve. If there's a function you need, simply define it:

deffunction_i_need(a):
     """parameter a: an instance of A"""pass# do something with 'a'

However, if I cannot dissuade you from making your function a method of the class, you can change an instance's class by setting its __class__ attribute:

>>>classA(object):...def__init__(self):...pass...>>>classB(A):...deffunctionIneed(self):...print'functionIneed'...>>>a = A()>>>a.functionIneed()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'functionIneed'
>>>a.__class__ = B>>>a.functionIneed()
functionIneed

This will work as long as B has no __init__ method, since, obviously, that __init__ will never be called.

Solution 3:

You said you want to implement something like this:

classB(A):
    deffunctionIneed():
        pass

But really what you would be making is something more like this (unless you had intended on making a class or static method in the first place):

classB(A):
    deffunctionIneed(self):
        pass

Then you can call B.functionIneed(instance_of_A). (This is one of the advantages of having to pass self explicitly to methods.)

Solution 4:

You did not correctly define your classes. Should be like this:

classA(object):def__init__(self):
        pass

classB(A):def__init__(self):
        super(B,self).__init__()

    deffunctionIneed(self):
        pass

Then you can

j=B()
j.fuctionIneed()

as expected

You forgot to refer to the ins

Solution 5:

Just thinking outside the box:

Instead of a new class with the function you want, how about just adding the function to the class or instance you already have?

There is a good description of this in Adding a Method to an Existing Object Instance

Post a Comment for "How To Convert (inherit) Parent To Child Class?"