calling child class method from parent class file in python

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

    Doing this would only make sense if A is an abstract base class, meaning that A is only meant to be used as a base for other classes, not instantiated directly. If that were the case, you would define methodB on class A, but leave it unimplemented:

    class A(object):
        def methodA(self):
            print("in methodA")
    
        def methodB(self):
            raise NotImplementedError("Must override methodB")
    
    
    from parent import A
    class B(A):
        def methodB(self):
            print("am in methodB")
    

    This isn't strictly necessary. If you don't declare methodB anywhere in A, and instantiate B, you'd still be able to call methodB from the body of methodA, but it's a bad practice; it's not clear where methodA is supposed to come from, or that child classes need to override it.

    If you want to be more formal, you can use the Python abc module to declare A as an abstract base class.

    from abc import ABCMeta, abstractmethod
    
    class A(object):
     __metaclass__ = ABCMeta
    
        def methodA(self):
            print("in methodA")
    
        @abstractmethod
        def methodB(self):
            raise NotImplementedError("Must override methodB")
    

    Using this will actually prevent you from instantiating A or any class that inherits from A without overriding methodB. For example, if B looked like this:

    class B(A):
       pass
    

    You'd get an error trying to instantiate it:

    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: Can't instantiate abstract class B with abstract methods methodB
    

    The same would happen if you tried instantiating A.

提交回复
热议问题