Home > Software engineering >  How python function A executed when call function B?
How python function A executed when call function B?

Time:11-01

The existing code is:

class Base:
    def hello(self):
        print('hello')


class A(Base):
    def greet(self):
        self.hello()
        print('how are you?')


class B(Base):
    def greet(self):
        self.hello()
        print('how are you doing?')

How can I write code to implement that call self.hello() firstly when call self.greet(), but not add self.hello() in each Class A and Class B?

I want to follow the Don't Repeat Yourself (DRY) principle.

CodePudding user response:

The reason you have duplicate code is because you are redefining the "greet" in your code. By recognizing that a greet always consists of the "hello" message followed by a question, you could implement that common functionality in the base class, and requiring the actual question to be implemented in the child class.

It's slightly more code for this simple example, but it demonstrates the general principle:

class Base:

    def hello(self):
        print('hello')

    def question(self):
        # this should be implemented in the derived classes
        raise NotImplementedError

    def greet(self):
        self.hello()
        self.question()


class A(Base):

    def question(self):
        print('how are you?')


class B(Base):

    def question(self):
        print('how are you doing?')


a = A()
b = B()
a.greet()
b.greet()

NB: You don't have to define the question() method in the base class (you could just leave it out and the code would still work), but it helps in documenting that subclasses must define this function and it will print a more helpful error message in case you accidentally try to call the question() method on an object of the base class. It might also avoid warnings when running linters (such as pylint or pycodestyle) and improve syntax highlighting / auto-completion when you are using an IDE (such as Visual Studio Code).

CodePudding user response:

In this scenario, I think you would like to define the basic behaviour in the Base class, allowing the subsequent classes to expand onto that behaviour by adding extra logic, not replacing it.

Here is a way to achieve this:

class Base:
    def hello(self):
        print('hello')

    def greet(self):
        self.hello()


class A(Base):
    def greet(self):
        super().greet()
        print('how are you?')


class B(Base):
    def greet(self):
        super().greet()
        print('how are you doing?')

Even though you are repeating the call to super().greet(), this is the way to do it in Python - because it needs to be explicitly called (for example in Java the parent is always called).

  • Related