SoFunction
Updated on 2024-12-16

Quick Start Python Guide to Object-Oriented Advancement

introductory

We had a preliminary introduction to object declarations in Python. In this installment, we will delve into the three core concepts of object inheritance, composition, and polymorphism. However, without going into too much theory here, we all know that the main difference between Python and Java in these areas is mainly in the syntax. For example, Python supports multiple inheritance, which means that a class can inherit properties and methods from more than one parent class at a time, whereas Java supports only single inheritance. Another noteworthy difference is the use of the super keyword. In Java, we often need to explicitly use super to call the constructor of the parent class, whereas in Python, this step is optional. If not specified, Python automatically calls the constructor of the parent class, which makes the code look cleaner.

Of course, we won't give too many complicated examples here to make your head hurt. After all, our goal is to understand and apply these concepts, not to prepare for an exam. We will use some simple and intuitive examples to help you clearly grasp the features and benefits of Python in terms of inheritance, composition, and polymorphism.

Inheritance of objects

Inheritance in Python is a mechanism used to create new classes that can inherit features from one or more parent classes. In object-oriented programming, as in Java, inheritance provides a powerful tool for code reuse.

class Animal:
    def __init__(self, name):
         = name
    def speak(self):
        pass
class Dog(Animal):
    # def __init__(self, name):
        # super().__init__(name)  
    def speak(self):
        return "Woof!"
# Use
dog = Dog("Buddy")
print(())  # Output: Woof!
print()  # exports: Buddy

If you don't declare __init__, the default is to use super to call the constructor of the parent class. If you do declare __init__, then remember to call super explicitly, otherwise it will be invalid.

Multiple inheritance is a powerful feature in Python that allows a class to inherit from more than one parent class at a time. Here is an example of multiple inheritance to help you better understand the concept:

class Father:
    def __init__(self):
        self.father_name = "Father's name"
    def gardening(self):
        return "I enjoy gardening"
class Mother:
    def __init__(self):
        self.mother_name = "Mother's name"
    def cooking(self):
        return "I love cooking"
class Child(Father, Mother):
    def __init__(self):
        Father.__init__(self)
        Mother.__init__(self)
        self.child_name = "Child's name"
    def activities(self):
        return f"{self.father_name} likes {()} and {self.mother_name} likes {()}."
# Use
child = Child()
child.father_name = "father"
child.mother_name = "mom"
print(())

Combination of objects

In Python, we can dynamically add new behavior or data to objects as needed during program execution, which is a very convenient way to handle a variety of complex and unforeseen programming situations. In contrast, Java is somewhat constrained for dynamic changes at runtime due to its static typing. In Java, all properties and methods must be explicitly defined at compile time.

class Printer:
    def print_document(self, content):
        return f"Printing: {content}"
class Scanner:
    def scan_document(self):
        return "Scanning a document"
class MultifunctionMachine:
    pass
# Dynamically add functionality
mfm = MultifunctionMachine()
 = Printer()
 = Scanner()
# Use of new features
print(.print_document("Hello World"))  # Output: Printing: Hello World
print(.scan_document())                # exports: Scanning a document

pass is a seemingly simple but unmissable keyword that I'm not quite sure I've mentioned before. In the world of Python, pass is a particularly interesting presence. Imagine a scenario where you're writing code that logically requires a statement, but you don't have the implementation ready, or you want to leave an empty block of code to be filled in later. At this point, pass is like a nifty little helper, standing there silently, telling the Python interpreter, "Hey, I'm here, but you can ignore me for now."

polymorphic

In order to make polymorphism more intuitive, I have prepared an example through which I believe the concept of polymorphism will become vivid and clear. In Python, polymorphism is shown very intuitively, and it is almost identical to Java's treatment in this regard.

class Animal:
    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
    def speak(self):
        return "Woof!"
class Cat(Animal):
    def speak(self):
        return "Meow!"
def animal_speak(animal):
    print(())
# Use
my_dog = Dog()
my_cat = Cat()
animal_speak(my_dog)  # Output: Woof!
animal_speak(my_cat)  # exports: Meow!

summarize

In this installment, we dive into Python's three core concepts of object inheritance, composition, and polymorphism. From the flexibility of inheritance, such as Python's multiple inheritance and the use of the super keyword, to the dynamic addition of properties in combinations, we break down the similarities and differences between Python and Java in each of these areas. Through concrete examples, we show the visual representation of polymorphism in Python, emphasizing its similarities with Java. These discussions not only help to understand Python's object model, but also contrast the different ways in which Java and Python approach object-oriented programming

The above is a Java developer rapid advancement Python guide to object-oriented advanced details, more about Python object-oriented information please pay attention to my other related articles!