Python makes it easy: how to design class inheritance more concisely

When using Python's object-oriented programming, we often encounter situations where subclasses need to be designed to handle any changes or additions to their parent classes without constant adjustments. This situation often occurs in the init method of a class, especially when dealing with inheritance.

To handle this situation gracefully, Python provides both conventions *argsand . **kwargsBefore diving into the main example, let's briefly understand what these conventions are:

*args: allows you to pass a variable number of non-keyword arguments to the function. These arguments are captured into a tuple.

**kwargs: Allows passing a variable number of keyword arguments to a function. These parameters are captured into a dictionary.

Armed with this knowledge, let's look at a scenario where these conventions can come into play.

Scenario: extending the parent class

Suppose we have a class A which accepts two parameters in its constructor:

class A:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2
        print(f"类A的构造函数带有参数: {arg1}, {arg2}")

Now, if we design a class B that inherits from class A, and we want class B to adapt to any changes in class A without having to modify class B every time, we can use and to make class B's *argsinit **kwargsmethod generic :

class B(A):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)  # 将所有参数传递给类A的构造函数
        print("类B的构造函数")

By designing class B this way, any change in the signature of class A's init method will not break our instantiation of class B as long as we ensure that the parameters passed to class B meet class A's update requirements .

For example:

b = B("Hello", "World") 
# 输出: 
# 类A的构造函数带有参数: Hello, World
# 类B的构造函数

Advantages of this approach:

  • Flexibility: Modifications of Class B to Class A remain resilient. This is especially useful in larger projects or libraries, e.g. class A might be part of a module that receives updates.

  • Maintainability: As the project grows, developers don't have to revisit class B every time class A changes.

  • Cleaner code: We capture all parameters in a generic way instead of processing each one individually, making the code cleaner and clearer.

Precautions:

Although this approach offers flexibility, it also requires caution:

Blindly passing all parameters can sometimes lead to unintended consequences, especially if class A's constructor is changed in a way that is incompatible with how class B is instantiated.

Debugging can be a bit difficult, as error messages may point to the superclass's constructor, rather than the derived class.

in conclusion:

Designing flexible constructors using *args and **kwargs is a powerful tool in the Python developer's toolbox, especially when dealing with inheritance. By understanding and adopting this approach, developers can ensure that their classes remain flexible and maintainable through change and iteration. As always, while flexibility is beneficial, it is also crucial to be careful and ensure that flexibility does not introduce unintended problems.

English

original

AI Good Book Recommendation

AI is changing with each passing day, but a high-rise building cannot be separated from a good foundation. Are you interested in learning about the principles and practice of artificial intelligence? Look no further! Our book on AI principles and practices is the perfect resource for anyone looking to gain insight into the world of AI. Written by leading experts in the field, this comprehensive guide covers everything from the basics of machine learning to advanced techniques for building intelligent systems. Whether you are a beginner or an experienced AI practitioner, this book has you covered. So why wait?

The principles and practices of artificial intelligence comprehensively cover the classics of various important systems of artificial intelligence and data science

Peking University Press, Principles and Practices of Artificial Intelligence Artificial Intelligence and Data Science From Entry to Mastery Explain the Principles of Machine Learning and Deep Learning Algorithms

Guess you like

Origin blog.csdn.net/robot_learner/article/details/132225481