Python - 类和实例

在Python中,是创建对象的蓝图。
它定义了该类的对象将具有的属性和行为。

1. 声明类

在Python中,使用class关键字声明一个类,后面跟着类的名称。

✏️ 语法

python
class 类名:
    # 在这里定义属性和方法

2. 类属性

类属性是类的特征或数据,
它们可以是变量或常量。

✏️ 语法

python
class 类名:
    属性1 = 值1
    属性2 = 值2

📘 示例

python
class Circle:
    pi = 3.14159
    radius = 1.0

3. 类方法

类方法是类的行为或功能,
它们可以在类的实例上调用。

✏️ 语法

python
class 类名:
    def 方法名(cls, 参数1, 参数2):
        # 方法体
        ...

📘 示例

python
class MathUtils:
    def add(cls, num1, num2):
        return num1 + num2

4. 类实例化

类实例化是创建类的实例的过程。
通过调用类名后跟括号来完成。

✏️ 语法

python
实例名 = 类名()

📘 示例

python
person = Person()

5. 构造函数

构造函数是一个特殊的方法,在从类创建对象时自动调用。
它用于初始化对象的属性。
在Python中,构造函数的方法名为__init__

✏️ 语法

python
class 类名:
    def __init__(self, 参数1, 参数2):
        # 属性初始化
        self.属性1 = 参数1
        self.属性2 = 参数2

📘 示例

python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height