How to convert (inherit) parent to child class?

后端 未结 5 1612
孤独总比滥情好
孤独总比滥情好 2020-12-09 22:59

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         


        
相关标签:
5条回答
  • 2020-12-09 23:17

    You said you want to implement something like this:

    class B(A):
        def functionIneed():
            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):

    class B(A):
        def functionIneed(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.)

    0 讨论(0)
  • 2020-12-09 23:20

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

    0 讨论(0)
  • 2020-12-09 23:24

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

    class A(object):
        def __init__(self):
            pass
    
    class B(A):
        def __init__(self):
            super(B,self).__init__()
    
        def functionIneed(self):
            pass
    

    Then you can

    j=B()
    j.fuctionIneed()
    

    as expected

    You forgot to refer to the ins

    0 讨论(0)
  • 2020-12-09 23:29

    How about:

    i = module.getObject() # i will get object that is class A
    try:
        i.functionIneed()
    except AttributeError:
        # handle case when u have a bad object
    

    Read up on duck typing.

    0 讨论(0)
  • 2020-12-09 23:39

    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:

    def function_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:

    >>> class A(object):
    ...     def __init__(self):
    ...         pass
    ... 
    >>> class B(A):
    ...     def functionIneed(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.

    0 讨论(0)
提交回复
热议问题