Python 面向对象编程(OOP):介绍与用法(1)

简介

面向对象编程(Object-Oriented Programming,OOP)是一种编程范式,用于结构化和复用代码。在 Python 中,OOP 是通过使用类(Class)和对象(Object)来实现的。

类与对象

类的定义

使用 class 关键字来定义一个类。

python 复制代码
class Dog:
    def __init__(self, name):
        self.name = name

对象的创建

通过调用类的构造函数(__init__ 方法)来创建对象。

python 复制代码
my_dog = Dog("Buddy")

实例方法

在类中定义的函数称为实例方法。

python 复制代码
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print("Woof, woof!")

继承与多态

继承

通过继承,子类可以重用父类的代码。

python 复制代码
class Animal:
    def make_sound(self):
        print("Some generic sound")

class Dog(Animal):
    def make_sound(self):
        print("Woof, woof!")

多态

多态允许我们使用父类类型的变量来存储子类类型的对象。

python 复制代码
my_animal = Animal()
my_dog = Dog()

animals = [my_animal, my_dog]
for animal in animals:
    animal.make_sound()

封装与抽象

封装

封装是将对象的状态(属性)和行为(方法)包装在一个单一的单位中。

python 复制代码
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.__age = age  # 私有属性

    def get_age(self):  # 访问器方法
        return self.__age

抽象

抽象是隐藏实现细节,只暴露必要的接口。

python 复制代码
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

静态方法与类方法

静态方法

不需要访问或修改类状态或实例状态的方法。

python 复制代码
class Dog:
    @staticmethod
    def run():
        print("The dog is running.")

类方法

需要访问类变量,但不需要访问实例变量的方法。

python 复制代码
class Dog:
    total_dogs = 0

    def __init__(self, name):
        self.name = name
        Dog.total_dogs += 1

    @classmethod
    def dog_count(cls):
        return cls.total_dogs

总结

面向对象编程(OOP)在 Python 中是一种非常有用的编程范式。它通过使用类和对象来增加代码的可读性、可维护性和可复用性。

相关推荐
AIFQuant2 小时前
如何通过股票数据 API 计算 RSI、MACD 与移动平均线MA
大数据·后端·python·金融·restful
x70x802 小时前
Go中nil的使用
开发语言·后端·golang
REDcker2 小时前
libwebsockets库原理详解
c++·后端·websocket·libwebsockets
源代码•宸3 小时前
Leetcode—47. 全排列 II【中等】
经验分享·后端·算法·leetcode·面试·golang·深度优先
Wyy_9527*3 小时前
行为型设计模式——状态模式
java·spring boot·后端
梅梅绵绵冰3 小时前
springboot初步2
java·spring boot·后端
0和1的舞者5 小时前
公共类的注意事项详细讲解
经验分享·后端·开发·知识·总结
小北方城市网5 小时前
Spring Cloud Gateway 自定义过滤器深度实战:业务埋点、参数校验与响应改写
运维·jvm·数据库·spring boot·后端·mysql
jason.zeng@15022075 小时前
POM构造Spring boot多模块项目
java·spring boot·后端
猿与禅5 小时前
Spring Boot 3.x 集成 Caffeine 缓存框架官方指南
spring boot·后端·缓存·caffeine