About Python overrides.Please tell me how it works.

Asked 2 years ago, Updated 2 years ago, 15 views

Please tell me about overrides.The following example describes a method with the same name as the inherited method.
When should I describe the override?Also, what are the advantages of that?I can learn grammar, but please tell me the meaning of using override.You can see that derivative class methods work.

Example sentence

class Book:
    def__init__(self, title, price):
        self.title=title
        self.price=price
    def printPrice (self, num):
        print(self.title+':', num, 'in books', self.price*num, 'yen')

Class ColorBook (Book):
    color='yellow'
    def printPrice (self, num):
        print(self.title+':', num, 'in books', self.price*num, 'yen')
        print(self.color)

book2=ColorBook ('Picture Book', 1380')
book2.printPrice(2)

Run Results

Picture book: 2,760 yen for 2 books
 Yellow

Environment: Windows 10

python

2022-09-30 17:57

1 Answers

The big benefit is
·Reduce the amount of code

Although it is difficult to realize the meaning of a class with only a single simple method, as shown in the example, it is used to "just a little" change the functionality of an existing class.As this is a method-by-method change, you must design and separate the elements that you want to change later.

If you start thinking about "more efficient design" instead of grammar, you will realize its usefulness.On the other hand, common processing is concentrated in the base class, making it difficult to deal with problems on the base class side, and because of the reaction, draft design is important.

When you're done learning grammar, learning "object orientation and design patterns" will expand the world.

For example, using C#, Java, C++, or other languages that itself is intended to be object oriented, you can feel this benefit when calling out language features in the first place, but Python may find it difficult to "get the vibe while using it."


2022-09-30 17:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.