2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Table of contents
1. Object-oriented programming concepts (OOP)
1.1 What are classes and objects?
1.3 Relationship between classes and objects
2.2 Abstract Classes and Methods
3.1 Class definition and instantiation
3.2 Class properties and methods
4.1 The concept of encapsulation
5.1 The concept of inheritance
6.1 The concept of polymorphism
7.1 The concept of introspection
7.2 Using Introspection for Dynamic Operations
8. Static methods and class methods
Previous volume: Python modularization and package management
Object-Oriented Programming (OOP) It is a programming paradigm that is implemented by organizing programs into a collection of objects. Objects contain not only data but also methods for operating these data. The core concepts of OOP include classes, objects, attributes, and methods.
- Class A class is a template or blueprint used to create an object. It defines the properties and behavior of an object.
- Object It is an instance of a class. Creating an object is to create a specific instance based on the class.
example:
- class Dog:
- # 类的初始化方法
- def __init__(self, name, age):
- self.name = name # 属性
- self.age = age # 属性
-
- # 方法
- def bark(self):
- return f"{self.name} says Woof!"
-
- # 创建对象
- my_dog = Dog("Rex", 5)
- print(my_dog.bark())
In Python, classes are accessed through class
Keyword definition. Functions in a class are called methods, and variables are called properties. Class methods are usually named withself
As the first argument, represents the instance itself.
example:
- class Cat:
- def __init__(self, name):
- self.name = name
-
- def meow(self):
- return f"{self.name} says Meow!"
-
- # 创建对象
- my_cat = Cat("Whiskers")
- print(my_cat.meow())
A class is a template for an object, defining its structure and behavior. An object is an instance of a class, and each object has independent properties and methods.
- class Person:
- def __init__(self, name, age):
- self.name = name
- self.age = age
-
- def greet(self):
- return f"Hello, my name is {self.name} and I am {self.age} years old."
-
- # 创建多个对象
- person1 = Person("Alice", 30)
- person2 = Person("Bob", 25)
-
- print(person1.greet())
- print(person2.greet())
A class is like a mold for making cookies, which defines the shape and size of the cookies. Objects are like specific cookies made from the mold, each cookie can have different flavors (attributes), but their shape and size (structure and behavior) are the same.
abstract It refers to simplifying complex problems in the real world by focusing on the main features and ignoring the details. In programming, abstraction helps us create more concise and maintainable code.
Abstraction is to extract the main features of an object and ignore unimportant details. Through abstraction, we can focus on the core functionality of the object without being distracted by minor features.
example:
- class Animal:
- def __init__(self, name):
- self.name = name
-
- def make_sound(self):
- pass # 抽象方法,不具体实现
-
- class Dog(Animal):
- def make_sound(self):
- return "Woof!"
-
- class Cat(Animal):
- def make_sound(self):
- return "Meow!"
-
- # 创建对象
- dog = Dog("Rex")
- cat = Cat("Whiskers")
-
- print(dog.make_sound())
- print(cat.make_sound())
In Python, we can achieve abstraction by defining abstract classes and abstract methods. Abstract classes cannot be instantiated, they can only be inherited. Abstract methods are defined in abstract classes but implemented in subclasses.
example:
- from abc import ABC, abstractmethod
-
- class Vehicle(ABC):
- @abstractmethod
- def start_engine(self):
- pass
-
- class Car(Vehicle):
- def start_engine(self):
- return "Car engine started"
-
- class Motorcycle(Vehicle):
- def start_engine(self):
- return "Motorcycle engine started"
-
- # 创建对象
- car = Car()
- motorcycle = Motorcycle()
-
- print(car.start_engine())
- print(motorcycle.start_engine())
Abstraction is like simplifying a complex painting into geometric shapes. For example, a specific cat has many characteristics (fur color, size, age, etc.), but we only focus on the characteristic that it meows, which is an abstraction of the cat.
Classes and instances It is the foundation of OOP. Classes are templates, and instances are concrete objects. Instances are created through classes and have the properties and methods defined by the class.
Defining a class and creating an instance are the basic operations of OOP. A class defines properties and methods, while an instance is a specific object of the class.
example:
- class Student:
- def __init__(self, name, grade):
- self.name = name
- self.grade = grade
-
- def introduce(self):
- return f"Hi, I am {self.name} and I am in grade {self.grade}."
-
- # 创建实例
- student1 = Student("Alice", 10)
- student2 = Student("Bob", 12)
-
- print(student1.introduce())
- print(student2.introduce())
The attributes of a class are the state of an object, and methods are the behavior of an object. __init__
Method initialization, the method is defined in the class.
example:
- class Book:
- def __init__(self, title, author):
- self.title = title
- self.author = author
-
- def get_info(self):
- return f"'{self.title}' by {self.author}"
-
- # 创建实例
- book = Book("1984", "George Orwell")
- print(book.get_info())
Classes and instances are like the blueprint of a house and the actual house. The blueprint (class) defines the structure and function of the house, while the actual house (instance) is the specific object built according to the blueprint.
Encapsulation It is to hide the state (attributes) and behavior (methods) of an object inside a class and interact with the outside world through interfaces (methods). Encapsulation improves the security and maintainability of the code.
Encapsulation is one of the core concepts of OOP, which protects the data of an object by hiding its internal state and exposing only necessary interfaces. In this way, external code cannot directly access or modify the internal state of the object, but can only operate the data through the methods provided by the object.
example:
- class Account:
- def __init__(self, owner, balance=0):
- self.owner = owner
- self.__balance = balance # 私有属性
-
- def deposit(self, amount):
- if amount > 0:
- self.__balance += amount
- else:
- raise ValueError("Deposit amount must be positive")
-
- def withdraw(self, amount):
- if 0 < amount <= self.__balance:
- self.__balance -= amount
- else:
- raise ValueError("Insufficient funds or invalid amount")
-
- def get_balance(self):
- return self.__balance
-
- # 创建实例
- account = Account("John")
- account.deposit(100)
- print(account.get_balance())
The interface is the only way for an object to interact with the outside world. Through the interface, external code can call the object's methods but cannot directly access the object's internal state.
example:
- class Car:
- def __init__(self, model):
- self.model = model
- self.__engine_started = False
-
- def start_engine(self):
- if not self.__engine_started:
- self.__engine_started = True
- return "Engine started"
- else:
- return "Engine is already running"
-
- def stop_engine(self):
- if self.__engine_started:
- self.__engine_started = False
- return "Engine stopped"
- else:
- return "Engine is not running"
-
- # 创建实例
- car = Car("Toyota")
- print(car.start_engine())
- print(car.stop_engine())
Encapsulation is like the shell of a mobile phone. The circuits and components (the state of the object) inside the phone are encapsulated inside the shell, and users can only interact with the phone through buttons and screens (interfaces), but cannot directly touch the internal components.
inherit It is another core concept of OOP, which allows us to create a new class based on an existing class, and the new class inherits all the properties and methods of the existing class.
Inheritance means that a class (subclass) obtains properties and methods from another class (parent class). Through inheritance, the subclass can reuse the parent class's code, add new properties and methods, or override the parent class's methods.
example:
- class Animal:
- def __init__(self, name):
- self.name = name
-
- def speak(self):
- pass
-
- class Dog(Animal):
- def speak(self):
- return "Woof!"
-
- class Cat(Animal):
- def speak(self):
- return "Meow!"
-
- # 创建实例
- dog = Dog("Rex")
- cat = Cat("Whiskers")
-
- print(dog.speak())
- print(cat.speak())
A subclass can override the method of the parent class, that is, define a method with the same name as the parent class in the subclass to achieve different functions.
example:
- class Shape:
- def area(self):
- return 0
-
- class Rectangle(Shape):
- def __init__(self, width, height):
- self.width = width
- self.height = height
-
- def area(self):
- return self.width * self.height
-
- class Circle(Shape):
- def __init__(self, radius):
- self.radius = radius
-
- def area(self):
- return 3.14 * (self.radius ** 2)
-
- # 创建实例
- rectangle = Rectangle(3, 4)
- circle = Circle(5)
-
- print(rectangle.area())
- print(circle.area())
Inheritance is like a legacy from parents to children. Parents (parent classes) pass their properties (attributes and methods) to their children (subclasses), and children can not only use these properties, but also become richer through their own efforts (adding new properties and methods).
Polymorphism It means that the same method has different representations on different objects. Polymorphism allows us to call methods of different objects through the same interface to achieve different functions.
Polymorphism is one of the important features of OOP. It allows the same method to have different implementations by pointing to the subclass object through the parent class reference. Polymorphism improves the flexibility and scalability of the code.
example:
- class Animal:
- def speak(self):
- pass
-
- class Dog(Animal):
- def speak(self):
- return "Woof!"
-
- class Cat(Animal):
- def speak(self):
- return "Meow!"
-
- def animal_sound(animal):
- print(animal.speak())
-
- # 创建实例
- dog = Dog()
- cat = Cat()
-
- animal_sound(dog)
- animal_sound(cat)
In Python, polymorphism is usually achieved through method overriding and parent class references. By pointing to the child class object through the parent class reference, the child class method can be called.
example:
- class Shape:
- def draw(self):
- pass
-
- class Rectangle(Shape):
- def draw(self):
- return "Drawing a rectangle"
-
- class Circle(Shape):
- def draw(self):
- return "Drawing a circle"
-
- def draw_shape(shape):
- print(shape.draw())
-
- # 创建实例
- rectangle = Rectangle()
- circle = Circle()
-
- draw_shape(rectangle)
- draw_shape(circle)
Polymorphism is like a universal remote control. Whether it is controlling a TV, air conditioner or stereo, as long as these devices have corresponding interfaces (methods), the remote control (parent class reference) can achieve different functions through the same buttons (method calls).
Self-reflection It means that an object can know its own information at runtime. Python provides some built-in functions for introspection, such astype()
、id()
、hasattr()
wait.
Introspection means that an object can obtain its own information at runtime, such as attributes, methods, etc. Introspection makes Python programs highly dynamic and flexible.
example:
- class Person:
- def __init__(self, name, age):
- self.name = name
- self.age = age
-
- person = Person("Alice", 30)
-
- # 使用内置函数进行自省
- print(type(person))
- print(hasattr(person, "name"))
- print(getattr(person, "name"))
- setattr(person, "name", "Bob")
- print(person.name)
- delattr(person, "name")
Through introspection, we can dynamically manipulate the properties and methods of an object at runtime, making the program more flexible and dynamic.
example:
- class Car:
- def __init__(self, model):
- self.model = model
- self.speed = 0
-
- def accelerate(self):
- self.speed += 5
- return self.speed
-
- car = Car("Toyota")
-
- # 动态操作对象
- if hasattr(car, "accelerate"):
- method = getattr(car, "accelerate")
- print(method())
- print(method())
-
- # 动态设置属性
- setattr(car, "color", "red")
- print(car.color)
Self-reflection is like a person looking in the mirror. Through the mirror (self-reflection mechanism), people can see what they look like (the properties and methods of the object) and make adjustments as needed (dynamic operation objects).
Static methods andClass Methods A static method is a method that is associated with a class, not an instance.@staticmethod
Decorator, class method use@classmethod
Decorator.
A static method is a method of a class, but it is not bound to any class instance. Static methods cannot access instances of a class, nor can they modify the state of a class. They are usually used to perform some operations that are not related to the class, but logically belong to the functionality of the class.
example:
- class Math:
- @staticmethod
- def add(a, b):
- return a + b
-
- print(Math.add(5, 3))
A class method is a method that is bound to a class rather than an instance. The first argument to a class method is the class itself, usually named cls
. Class methods can access class attributes and other class methods.
example:
- class Math:
- factor = 2
-
- @classmethod
- def multiply(cls, value):
- return cls.factor * value
-
- print(Math.multiply(5))
Various aspects of object-oriented programming in Python, including the basic concepts of object-oriented programming, abstraction, classes and instances, encapsulation, inheritance, polymorphism, introspection, and static methods and class methods.
I hope this detailed blog helps you gain a deeper understanding of object-oriented programming in Python and apply this knowledge in real-world projects. If you have any questions or need further assistance, please feel free to contact me!