Article directory
- Three major characteristics of object-oriented
- Summarize
Three major characteristics of object-oriented
Object-oriented programming has three major characteristics: encapsulation, inheritance and polymorphism.
- Encapsulation: Encapsulation ensures the security of data in an object by encapsulating data and methods of operating data in an object to avoid direct external access to the object's data.
- Inheritance: Inheritance ensures the scalability of objects. Subclasses can inherit the attributes and methods of the parent class and can be extended on this basis.
- Polymorphism: Polymorphism ensures the flexibility of the program and allows objects of different types to respond differently to the same message.
Object-oriented programming basics such as classes and objects
In object-oriented programming, we usually define classes and objects. A class is an abstract description of a class of similar objects, while objects are concrete instances. Let's take a look at the concepts of classes and objects and the relationship between them.
define a class
class A(object):
# 类属性
count = 0
def __init__(self):
# 实例属性
self.name = '孙悟空'
def test(self):
# 实例方法
print('这是test方法~~~', self)
@classmethod
def test_2(cls):
# 类方法
print('这是test_2方法,他是一个类方法~~~', cls)
print(cls.count)
@staticmethod
def test_3():
# 静态方法
print('test_3执行了~~~')
In the above code, we have defined a class A
. in:
count
Is a class attribute that can be accessed through a class or instance and can only be modified through a class object.__init__()
It is a constructor method used to initialize instance properties and is automatically called when creating an object.test()
It is an instance method that takesself
as the first parameter and operates instance properties.test_2()
It is a class method that takescls
as the first parameter and operates class attributes.test_3()
It is a static method, does not need to specify default parameters, and has nothing to do with the current class.
Create objects and call methods
a = A()
a.test()
A.test_2()
A.test_3()
In the above code, we create an object a
and then call the instance method through the instance object test()
. Next, we called class methods test_2()
and static methods through the class object test_3()
.
This is the basic concept and use of classes and objects. Next, we will continue to explore other features in object-oriented programming.
Object-oriented programming basics: inheritance and polymorphism
In object-oriented programming, inheritance and polymorphism are two important concepts that can improve code reusability and flexibility. Let us learn the usage and characteristics of inheritance and polymorphism together.
inherit
Inheritance is a mechanism in object-oriented programming that allows us to create a new class that inherits from one or more existing classes. The inherited class is called the parent class (or base class), and the newly created class is called the subclass (or derived class). Subclasses inherit the properties and methods of the parent class and can be extended and modified on this basis.
# 定义一个父类
class Parent(object):
def __init__(self):
self.parent_attr = '父类属性'
def parent_method(self):
print('这是父类方法')
# 定义一个子类,继承父类
class Child(Parent):
def __init__(self):
# 调用父类的构造方法
super().__init__()
self.child_attr = '子类属性'
def child_method(self):
print('这是子类方法')
In the above code, we define a parent class Parent
and a child class Child
. The subclass Child
inherits the parent class Parent
and super().__init__
obtains the properties and methods of the parent class by calling the parent class's constructor. Subclasses can add their own properties and methods on top of this.
Polymorphism
Polymorphism is a very powerful feature in object-oriented programming. It allows us to use the reference of the parent class to point to the object of the subclass, thereby achieving flexible code design. Polymorphism allows us to handle objects of different subclasses in a unified manner.
# 使用多态调用父类方法
def invoke_method(obj):
obj.parent_method()
# 创建父类和子类对象
parent = Parent()
child = Child()
# 调用父类方法
invoke_method(parent)
invoke_method(child)
In the above code, we define a invoke_method
function that accepts a parent class object as a parameter and calls the parent class's method. Then, we create a parent class object parent
and a child class object child
and pass them to invoke_method
the function for call respectively. Due to the characteristics of polymorphism, whether it is a parent class object or a subclass object, the methods of the parent class can be called normally.
Inheritance and polymorphism are very important concepts and techniques in object-oriented programming, which can greatly improve the maintainability and scalability of the code.
Polymorphism is one of the three major characteristics of object-oriented
Polymorphism is an important feature in object-oriented programming, which allows objects of different types to respond differently to the same message. In the concept of polymorphism, an object can be presented in multiple forms.
Define two classes
First, we define two classes A and B and add some methods and properties to them. These two classes represent different object types respectively.
class A:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
class B:
def __init__(self, name):
self._name = name
def __len__(self):
return 10
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
class C:
pass
a = A('孙悟空')
b = B('猪八戒')
c = C()
define a function
Next, we define a function say_hello(obj)
that accepts one parameter obj
. This function does not consider the specific type of the object. As long as the object contains name
attributes, it can be passed to the function as a parameter.
def say_hello(obj):
print('你好 %s' % obj.name)
At this point, we can call say_hello
the function and pass in objects of different types as parameters, and the function will print the corresponding greeting based on the properties of the object.
say_hello(a) # 输出:你好 孙悟空
say_hello(b) # 输出:你好 猪八戒
duck type
In object-oriented programming, duck typing is a dynamic typing concept. It bases the suitability of objects on the methods and properties they possess, rather than through inheritance relationships or implementation of specific interfaces.
Let's take len()
functions as an example. As long as an object has __len__
a special method, you can len()
get its length.
l = [1, 2, 3]
s = 'hello'
print(len(l)) # 输出:3
print(len(s)) # 输出:5
print(len(b)) # 输出:10
print(len(c)) # 报错:AttributeError: 'C' object has no attribute '__len__'
In the above code, we can see that through len()
the function, the length of the list l
and string can be obtained s
, but C
the length of the class cannot be obtained. This is because classes B
define __len__
methods, while classes C
do not.
Encapsulation and abstraction based on object-oriented programming
In object-oriented programming, encapsulation and abstraction are two important concepts that help us better organize and manage code. Let us learn the usage and characteristics of encapsulation and abstraction.
encapsulation
Encapsulation is a mechanism in object-oriented programming that encapsulates data and methods of operating data in a unit and hides specific implementation details from the outside. Through encapsulation, we can organize data and methods into a logical whole, improving the readability and maintainability of the code.
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_age(self):
return self.age
def set_age(self, age):
self.age = age
student = Student('张三', 18)
print(student.get_name()) # 输出:张三
print(student.get_age()) # 输出:18
student.set_name('李四')
student.set_age(20)
print(student.get_name()) # 输出:李四
print(student.get_age()) # 输出:20
In the above code, we define a Student
class that encapsulates the student's name and age attributes and provides methods for getting and setting attribute values. In this way, we can control the access permissions of the attributes, as well as perform reasonable verification and processing of the attributes.
abstract
Abstraction is an important principle in object-oriented programming, which abstracts common properties and methods into an abstract class or interface. Abstract classes cannot be instantiated and can only serve as parent classes for other classes. Subclasses must implement all abstract methods defined in the abstract class.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print('汪汪汪')
class Cat(Animal):
def make_sound(self):
print('喵喵喵')
#animal = Animal() # 错误,抽象类不能被实例化
dog = Dog()
dog.make_sound() # 输出:汪汪汪
cat = Cat()
cat.make_sound() # 输出:喵喵喵
In the above code, we define an abstract class Animal
, which contains an abstract method make_sound()
. This abstract method has no specific implementation, but is left to subclasses to implement. Then, we created Dog
two Cat
subclasses and implemented abstract methods respectively. Through the use of abstract classes, we can ensure that specific methods will be implemented in subclasses.
Encapsulation and abstraction are very important concepts and techniques in object-oriented programming, which can help us build more reliable and scalable code.
Object-oriented programming basics: composition and interfaces
In object-oriented programming, in addition to inheritance and polymorphism, there are two important concepts: composition and interfaces. Let's learn the usage and characteristics of combinations and interfaces.
combination
Composition refers to combining different classes together to form a larger class. Through composition, we can reference objects of other classes in one class as its properties to build more complex object structures.
class Engine:
def start(self):
print("引擎启动")
def stop(self):
print("引擎停止")
class Car:
def __init__(self):
self.engine = Engine()
def drive(self):
self.engine.start()
print("汽车行驶中")
self.engine.stop()
car = Car()
car.drive()
In the above code, we have defined a Car
class and a Engine
class. Classes implement the combination of engines Car
by using objects as attributes. Engine
In this way, we can Car
call Engine
the object's method in the class to implement the start and stop functions of the car.
interface
An interface is a convention that specifies what properties and methods a class should have. In object-oriented programming, an interface describes a set of related operations but has no specific implementation. Through interfaces, we can define a common set of behavioral standards to achieve code flexibility and replaceability.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
def perimeter(self):
return 2 * 3.14 * self.radius
rectangle = Rectangle(5, 3)
print(rectangle.area()) # 输出:15
print(rectangle.perimeter()) # 输出:16
circle = Circle(4)
print(circle.area()) # 输出:50.24
print(circle.perimeter()) # 输出:25.12
In the above code, we define an Shape
interface, which contains two abstract methods area()
and perimeter()
. Then, we created two Shape
subclasses that implement the interface: Rectangle
and Circle
. Through the use of interfaces, we can ensure that all classes that implement Shape
the interface have the same methods, thereby achieving unified processing of code.
Composition and interfaces are very important concepts and techniques in object-oriented programming, which can help us build more flexible and extensible code.
Summarize
Object-Oriented Programming (OOP for short) is a programming paradigm for organizing and managing code. It is based on the concept of objects, encapsulating data and operations in an independent entity, and achieving code flexibility, readability, and maintainability through interactions between classes.
Object-oriented programming has the following basic characteristics:
Encapsulation: Encapsulate data and operations on data in an entity, hide internal implementation details through access control, and improve code security and modularity.
Inheritance: Through the inheritance mechanism, a class can be derived from another class, inherit the attributes and methods of the parent class, and extend or modify it on this basis to achieve code reuse and hierarchical design.
Polymorphism: The same method can produce different behaviors when called on different objects. Through polymorphism, a unified interface can be used to handle different types of objects, improving the flexibility and scalability of the code.
Abstraction: Define specifications and constraints through abstract classes or interfaces, hide implementation details, emphasize the high-level logic and overall architecture of the code, and improve the modularity and maintainability of the code.
In object-oriented programming, we can create objects by defining classes and call object methods to achieve specific functions. By combining multiple objects, we can build more complex systems and data structures.
In addition, object-oriented programming also introduces some design principles and patterns, such as the single responsibility principle, the open-closed principle and design patterns, etc., to help us design codes with high cohesion, low coupling, scalability and easy maintenance.
By learning the basics of object-oriented programming, we can better understand and apply this programming paradigm and improve our software development capabilities.