亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python 面向对象编程基础:类、对象、继承与构造函数详解

Python 面向对象编程 (OOP)

Python 的 OOP 模型让开发者将现实实体建模为由 类 定义的 对象。语言优先代码复用与模块化,创建和扩展类直观简单。

什么是类?

类是捆绑数据(属性)与行为(方法)的逻辑容器。它定义共享公共属性的对象模板。

示例:Customer 类可暴露 transactions、balance、debt 等属性,及 deposit()、withdraw() 等方法。

在 Python 中定义类

创建简单类的步骤:

  1. 用 class 关键字:
    class MyClass: pass
  2. 在类内定义方法。实例方法第一个参数是 self,指代对象自身。
    class MyClass:
        def greet(self):
            print("Hello from MyClass")
  3. 实例化类:
    obj = MyClass()
  4. 调用其方法:
    obj.greet()

完整示例:

# Python 类工作示例
class MyClass:
    def method1(self):
        print("Guru99")
    def method2(self, text):
        print("Software Testing: " + text)

def main():
    c = MyClass()
    c.method1()
    c.method2(" Testing is fun")

if __name__ == "__main__":
    main()

Python 继承

继承允许 派生类 复用并扩展 基类 行为。Python 支持单继承与多重继承。

class Base:
    def greet(self):
        print("Hello from Base")

class Derived(Base):
    def greet(self):
        super().greet()
        print("Hello from Derived")

# 使用
obj = Derived()
obj.greet()

关键点:

构造函数:__init__

__init__ 方法用预定义值初始化新对象。

class User:
    def __init__(self, name):
        self.name = name
    def say_hello(self):
        print(f"Welcome to Guru99, {self.name}")

user = User("Alex")
user.say_hello()

输出:Welcome to Guru99, Alex

Python 2 vs Python 3

仅有细微语法差异。上述示例在两版本均可工作(调整 print 语句)。

核心要点

Python

  1. 树莓派与Python构建机器人:完整指南
  2. C# 类与对象:面向对象编程的基石
  3. C++ Struct 与 Class 核心差异、语法及最佳实践
  4. 精通 Python 面向对象编程:类、继承、封装与多态
  5. 精通 Python 对象与类:实战指南
  6. 精通 Python 继承:概念、语法与实战示例
  7. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  8. Python collections.Counter:高效计数、更新与算术运算
  9. 理解 Python type() 与 isinstance():实战示例详解
  10. Python list.index() 详解:查找元素位置的实用指南与示例
  11. Python 面向对象编程完全指南:从基础到进阶
  12. 精通 Java:理解对象、类与核心 OOP 概念