calling child class method from parent class file in python

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

parent.py:

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

child.py:

from paren         


        
5条回答
  •  后悔当初
    2021-02-04 02:00

    There are three approaches/ways to do this ! but I highly recommend to use the approach #3 because composition/decoupling has certain benefits in terms of design pattern. (GOF)

    ## approach 1 inheritance 
    class A():
        def methodA(self):
            print("in methodA")
        def call_mehtodB(self):
            self.methodb()
    
    class B(A):
        def methodb(self):
            print("am in methodb")
    
    b=B()
    b.call_mehtodB()
    
    
    ## approach 2 using abstract method still class highly coupled
    from abc import ABC, abstractmethod
    class A(ABC):
        def methodA(self):
            print("in methodA")
        @abstractmethod    
        def methodb(self):
           pass
    
    class B(A):
    
        def methodb(self):
            print("am in methodb")
    
    b=B()
    b.methodb()
    
    #approach 3 the recommended way ! Composition 
    
    class A():
        def __init__(self, message):
            self.message=message
    
        def methodA(self):
            print(self.message)
    
    class B():
        def __init__(self,messageB, messageA):
            self.message=messageB
            self.a=A(messageA)
    
        def methodb(self):
            print(self.message)
    
        def methodA(self):
            print(self.a.message)
    
    b=B("am in methodb", "am in methodA")
    b.methodb()
    b.methodA()
    

提交回复
热议问题