calling child class method from parent class file in python

后端 未结 5 1415
名媛妹妹
名媛妹妹 2021-02-04 01:01

parent.py:

class A(object):
    def methodA(self):
        print(\"in methodA\")

child.py:

from paren         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 01:50

    You can do something like this:

    class A():
        def foo(self):
            self.testb()
    
    class B(A):
        def testb(self):
            print('lol, it works')
    b = B()
    b.foo()
    

    Which would return this of course:

    lol, it works
    

    Note, that in fact there is no call from parent, there is just call of function foo from instance of child class, this instance has inherited foo from parent, i.e. this is impossible:

    a=A()
    a.foo()
    

    will produce: AttributeError: A instance has no attribute 'testb'

    because

    >>> dir(A)
    ['__doc__', '__module__', 'foo']
    >>> dir(B)
    ['__doc__', '__module__', 'foo', 'testb']
    

    What I've wanted to show that you can create instance of child class, and it will have all methods and parameters from both parent and it's own classes.

提交回复
热议问题