I. Introduction
Abstract classes, polymorphism, and duck typing in Python are all mechanisms to achieve code flexibility, but there are some differences between them.
2. The difference between the three
- Abstract class: Requires subclasses to implement certain methods, thus standardizing the implementation of subclasses.
- Polymorphism: The same method can be implemented differently for different types of objects, improving the flexibility of the code.
- Duck typing: Doesn't care about the type of the object, only cares about whether the object has certain methods or properties.
3. Concepts and sample code
1. Polymorphism
1.1 Three forms of polymorphism:
- Inherit abstract class
- The degree of coupling is extremely high and the scalability of the program is extremely low.
- Inherit from parent class
- High degree of coupling and low program scalability
- duck type
- Low coupling and high program scalability
1.2 Purpose of polymorphism:
In order to unify the specification (name) of object calling methods without knowing the specific type of the object.
Parent class: Customize a unified set of specifications. (For example: unified method names)
Subclass: Follow the unified specifications of the parent class. (For example: subclasses follow the unification of parent class method names)
1.3 Benefits of polymorphism:
- It increases the flexibility of the program
and adapts to changes in the same way. No matter the objects are ever-changing, users can call them in the same form, such asfunc(people1)
- Increases the scalability of the program.
A new class is created by inheriting the animal class. Users do not need to change their own code and stillfunc(people1)
use call
1.4 Polymorphic sample code
class People(Animal): #属于动物的另外一种形态:人
def speak(self):
print('say hi')
def func(people): #对于使用者来说,自己的代码根本无需改动
people.speak()
people1=People() #实例出一个人
func(people1) #甚至连调用方式也无需改变,就能调用人的talk功能
'''
这样我们新增了一个形态People,由People类产生的实例people1,使用者可以在完全不需要修改自己代码的情况下,
使用和猫、狗、猪一样的方式调用people1的speak方法,即func(people1)
'''
Sample code two
class Shape:
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
def print_area(shape):
print(shape.area())
s = Square(5)
c = Circle(3)
print_area(s) # 25
print_area(c) # 28.26
In the above code, Shape
the class is a base class and defines a method area()
. Square
and Circle
classes inherit from Shape
classes and implement their own area()
methods respectively. print_area()
The function accepts a Shape
type of parameter, and Shape
objects of different types will produce different behaviors, achieving polymorphism.
2. Abstract class
2.1 What is an abstract class?
In python's built-in abc module, there is an abstract class that allows subclasses to follow the writing specifications of the parent class.
2.2 How to implement abstract classes
- The parent class needs to inherit metaclass=abc.ABCMeta in the abc module
- In the method of the parent class, you need to decorate it with abc.abstractmethod
Notice:
-
Using abstract classes is deprecated in python.
-
Subclasses must write specifications according to the methods of the parent class, and both are indispensable. (As long as there are several abstract methods in the parent class, the subclass must define a few, you can have more, but not less)
2.3 Abstract class sample code
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# 不能实例化Shape
# s = Shape()
sq = Square(5)
c = Circle(3)
print(sq.area()) # 25
print(c.area()) # 28.26
In the above code, Shape
the class is an abstract class and defines an abstract method area()
. Square
The and Circle
classes inherit Shape
the class and implement their own area() methods respectively. Because Shape
it is an abstract class, it cannot be instantiated directly and can only be instantiated through subclasses.
3. Duck Type
3.1 What is duck typing
- Python advocates duck type. Different objects, as long as they look like a duck and act like a duck, then it is a duck.
- Duck typing is a form of polymorphism.
3.2 Why duck typing is necessary
For different objects, first abstract methods of the same type and customize a unified set of specifications for them. All classes are written according to unified specifications when defined.
3.3 Duck typing example code
class Duck:
def quack(self):
print("Quack")
class Person:
def quack(self):
print("I'm quacking like a duck")
def duck_test(obj):
obj.quack()
d = Duck()
p = Person()
duck_test(d) # Quack
duck_test(p) # I'm quacking like a duck
In the above code, both the Duck
and Person
class have a quack()
method, duck_test()
and the function accepts an object parameter. As long as the object has a quack()
method, it does not care about its specific type, and duck typing is implemented.
4. Summary:
- An abstract class is a special class that cannot be instantiated. Its role is to regulate the behavior of subclasses.
- Polymorphism is a feature based on inheritance. The same method can be implemented differently for different types of objects.
- Duck typing is a dynamic typing mechanism that focuses on the behavior of the object rather than its type. As long as an object implements a specific interface, it can be regarded as the implementation object of the interface.
The above is an introduction to the differences and usage of Python - [polymorphism, abstract class, duck type], I hope it will be helpful to you!