简体   繁体   中英

In Python, how should I implement an Inherited class with the exact same properties and methods as the Parent class?

I'm doing a project with Python and have defined a base class called Encoder :

class Encoder:
    def __init__(self):
        ...

    def encode(self, text):
        ...

Now I want to create two child classes called RotatingEncoder and StaticEnocder that inherit from this class.

class RotatingEncoder(Encoder):
    def __init__(self, rotor_size=26):
        ...
        # do stuff
        ...
        super().__init__()

    def encode(self, text):
        ...
        # do stuff
        ...
        return super().encode(text)

Defining RotatingEnocder is easy, but I have a few doubts regarding how to define StaticEnocder .

A StaticEncoder works exactly like an Encoder object. All its properites and methods are the same. But how do I define it? Here are two methods I thought of:

# Method A
class StaticEncoder(Encoder):
    pass


# Method B
class StaticEncoder(Encoder):
    def __init__(self):
        super().__init__()

    def encode(self, text):
        return super().encode(text)

Should I use one of these, or any other method? I would like my code to be as readable, and Pythonic, as possible

If it is absolutely required that Encoder be a non-abstract base class, Method A is best:

class StaticEncoder(Encoder):
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM