Article directory
[Python Basics]-07 Basic knowledge of object-oriented programming (1)
3. Inheritance
Inheritance is an important concept in object-oriented programming in Python, which allows us to create a new class and inherit properties and methods from one or more existing classes (called parent or base classes). Let us understand the concept of inheritance in detail and illustrate it with a case.
3.1 The concept of inheritance
Inheritance is a mechanism that allows a class (called a subclass or derived class) to inherit properties and methods from another class (called a parent or base class). Subclasses inherit the properties of the parent class and can add new features of their own or override inherited methods.
3.2 Syntax of Inheritance
In Python, inheritance is achieved by specifying the parent class in the definition of the subclass. The syntax is as follows:
class ChildClass(ParentClass):
# 子类的定义
3.3 Examples of Inheritance
Let's illustrate the concept of inheritance with an example:
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
print("动物发出声音")
class Dog(Animal):
def sound(self):
print("狗在汪汪叫")
class Cat(Animal):
def sound(self):
print("猫在喵喵叫")
dog = Dog("旺财")
cat = Cat("咪咪")
dog.sound() # 输出 "狗在汪汪叫"
cat.sound() # 输出 "猫在喵喵叫"
In the above case, we defined a Animal
parent class called , which has a sound
method for printing animal sounds. Then we created two subclasses Dog
and Cat
, which inherit Animal
the class. The method is rewritten in the subclass sound
to realize the sound of dog barking and cat barking respectively.
By creating instances of Dog
the and Cat
classes and calling their sound
methods, we can see that they bark and meow respectively. This is the role of inheritance, subclasses can inherit the characteristics of the parent class, and modify or extend it as needed.
3.4 Multiple inheritance
In addition to single inheritance, Python also supports multiple inheritance, that is, a subclass can inherit from multiple parent classes. The syntax is as follows:
class ChildClass(ParentClass1, ParentClass2):
# 子类的定义
Multiple inheritance allows subclasses to inherit properties and methods from multiple parent classes while possessing the characteristics of multiple parent classes.
Inheritance is a very powerful and flexible feature in object-oriented programming, which makes code reuse and extension easier. Through inheritance, we can use
Create related classes with different behaviors without repeating the same code. This improves code maintainability and scalability.
4. Packaging
In Python's object-oriented programming, encapsulation is an important concept that allows data and related methods to be combined into a whole, and the implementation details are hidden from the outside. Through encapsulation, we can control access to the internal properties and methods of the class, improving the security and maintainability of the code. Let us understand the concept of encapsulation in detail and illustrate it with a case.
4.1 The concept of encapsulation
Encapsulation is a mechanism for wrapping data and methods together in order to achieve information hiding and protect data consistency. In classes, we can use access modifiers to control the access level of properties and methods. Common access modifiers are public, protected, and private.
- Public: Properties and methods can be accessed from outside the class.
- Protected: Properties and methods can only be accessed within the class and its subclasses.
- Private: Properties and methods can only be accessed inside the class.
4.2 Case of Encapsulation
Let's illustrate the concept of encapsulation with an example:
class Person:
def __init__(self, name, age):
self.name = name
self._age = age # 保护属性,约定以单下划线开头
self.__address = "北京" # 私有属性,约定以双下划线开头
def display_info(self):
print(f"姓名:{
self.name}")
print(f"年龄:{
self._age}")
print(f"地址:{
self.__address}")
person = Person("Mingfeng", 25)
person.display_info()
In the above case, we defined a Person
class named , which has a public property name
, a protected property _age
, and a private property __address
. In the methods of the class, we can directly access these properties.
By creating Person
an instance of the class and calling display_info
the method, we can see that the outside of the class can access public name
and protected properties _age
, but cannot directly access private properties __address
. Private properties can be accessed in specific ways, such as using _类名__属性名
the form (eg _Person__address
).
Through encapsulation, we can hide the internal implementation details of the class, prevent external direct access and modification of attributes, and improve the security and maintainability of the code. Encapsulation also provides better code organization and structure, making code more readable and understandable.
It should be noted that encapsulation is not intended to restrict access, but to provide a good programming practice to make the code more robust and extensible. We should choose the appropriate visit
Ask modifiers, and follow certain conventions to write object-oriented code.
5. Polymorphism
In object-oriented programming in Python, polymorphism is an important concept that allows different objects to respond differently to the same method. Polymorphism can improve the flexibility and scalability of the code, so that we can write common code to deal with various objects. Let us understand the concept of polymorphism in detail and illustrate it with a case.
5.1 The concept of polymorphism
Polymorphism refers to multiple forms of objects. In object-oriented programming, polymorphism means that the same behavior can be performed by different objects, that is, different objects can respond differently to the same method. Polymorphism allows us to write more general code and improve code reusability and scalability.
5.2 Implementation of Polymorphism
Polymorphism can be achieved through method overriding and method overloading. Method rewriting refers to redefining existing methods in the parent class in the subclass to achieve different behaviors. Method overloading refers to defining multiple methods in the same class, they have the same name but different parameter types or number of parameters, so as to achieve different behaviors.
5.3 The case of polymorphism
Let's illustrate the concept of polymorphism with an example:
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("汪汪汪!")
class Cat(Animal):
def sound(self):
print("喵喵喵!")
def make_sound(animal):
animal.sound()
dog = Dog()
cat = Cat()
make_sound(dog) # 输出 "汪汪汪!"
make_sound(cat) # 输出 "喵喵喵!"
In the above case, we defined a Animal
parent class named , which has a sound
method named . Then we created two subclasses Dog
and Cat
, which respectively override sound
methods to achieve different sounds.
We can achieve polymorphism by passing in different animal objects in the function by defining a make_sound
function named , which takes a Animal
parameter of a type, and calls its method. sound
Whether it is Dog
an object or Cat
an object, they all respond to sound
methods and emit their own sounds.
Polymorphism allows us to write generic code that performs the same operations on different objects. In this way, we can handle various types of objects more flexibly, and improve code reusability and scalability.
summary:
Polymorphism is an important concept in object-oriented programming, which allows different objects to respond differently to the same method. Through method overriding and method overloading, we can achieve polymorphism. Polymorphism provides a more flexible and extensible way of writing code, improving code reusability and maintainability.
in conclusion
From this introduction, you should now have a basic understanding of object-oriented programming in Python. Object-oriented programming is a powerful programming paradigm that can improve code readability and maintainability, and provides features such as encapsulation, inheritance, and polymorphism. I hope this article helps you learn object-oriented programming in Python, and I wish you progress in your programming journey!