calling child class method from parent class file in python

后端 未结 5 1411
名媛妹妹
名媛妹妹 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:58

    You could use the function anywhere so long as it was attached to an object, which it appears to be from your sample. If you have a B object, then you can use its methodb() function from absolutely anywhere.

    parent.py:

    class A(object):
        def methoda(self):
            print("in methoda")
    
    def aFoo(obj):
      obj.methodb()
    

    child.py

    from parent import A
    class B(A):
        def methodb(self):
            print("am in methodb")
    

    You can see how this works after you import:

    >>> from parent import aFoo
    >>> from child import B
    >>> obj = B()
    >>> aFoo(obj)
    am in methodb
    

    Granted, you will not be able to create a new B object from inside parent.py, but you will still be able to use its methods if it's passed in to a function in parent.py somehow.

提交回复
热议问题