一、Python面向对象编程(OOP)简介
面向对象编程(OOP)是一种编程范式,它将程序组织成“对象”,每个对象都包含数据(属性)和操作数据的方法。Python 充分支持 OOP,使用 class 关键字定义类,并通过类创建对象。一个类就像一个蓝图,用于创建多个具有相同属性和方法的对象。
类包含:
示例:
立即学习“Python免费学习笔记(深入)”;
class Animal: def __init__(self, secret_attribute="secret"): # 构造函数,创建对象时自动执行 self.num_eyes = 2 self.__secret_attribute = secret_attribute # 私有变量,用双下划线开头 def breathe(self): print("吸气,呼气。") def get_secret_attribute(self): return self.__secret_attribute def make_sound(self): pass # 留给子类实现
二、OOP的核心概念
class Fish(Animal): def __init__(self): super().__init__() # 调用父类的构造函数 def breathe(self): super().breathe() # 调用父类的方法 print("在水下呼吸。") def swim(self): print("在水中游动。")
class Dog(Animal): def make_sound(self): return "汪!" class Cat(Animal): def make_sound(self): return "喵!" animals = [Dog(), Cat()] for animal in animals: print(animal.make_sound()) # 根据对象类型调用相应的方法
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass class Dog(Animal): def make_sound(self): return "汪!" perfect_dog = Dog() print(perfect_dog.make_sound()) # 输出 "汪!"
通过理解和运用这些核心概念,可以编写更模块化、可重用和易于维护的Python程序。
以上就是Python OOP的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号