菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python classmethod() 函数

Python3 内置函数 Python3 内置函数


classmethod() 是 Python 中用于将方法转换为类方法的内置函数。

类方法是属于类而不是实例的方法,第一个参数是类本身(通常命名为 cls)。类方法可以访问类的属性,但不能访问实例属性。

单词释义: classmethod 是 class method(类方法)的缩写。


基本语法与参数

语法格式

classmethod(function)

参数说明

  • 参数 function:
    • 类型: 函数对象
    • 描述: 要转换为类方法的函数。

函数说明

  • 返回值: 返回一个类方法对象。
  • 特点: 第一个参数是类本身(cls),不是实例(self)。

实例

示例 1:基础用法

实例

class MyClass:
class_attr = 0

@classmethod
def increment(cls):
cls.class_attr += 1
return cls.class_attr

@classmethod
def get_count(cls):
return cls.class_attr

# 通过类调用(不需要创建实例)
print(MyClass.increment()) # 输出: 1
print(MyClass.increment()) # 输出: 2
print(MyClass.get_count()) # 输出: 2

# 也可以通过实例调用(但不常见)
obj = MyClass()
print(obj.increment()) # 输出: 3

运行结果预期:

1
2
2
3

代码解析:

  1. 类方法通过 @classmethod 装饰器定义。
  2. 第一个参数是 cls,代表类本身。

示例 2:工厂方法

实例

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

@classmethod
def from_dict(cls, data):
"""从字典创建对象"""
return cls(data['name'], data['age'])

@classmethod
def from_string(cls, s):
"""从字符串创建对象(格式:name-age)"""
name, age = s.split('-')
return cls(name, int(age))

def __str__(self):
return f"{self.name}, {self.age}岁"

# 使用类方法的工厂模式
p1 = Person.from_dict({'name': 'Tom', 'age': 20})
p2 = Person.from_string("Jerry-25")

print(p1) # 输出: Tom, 20岁
print(p2) # 输出: Jerry, 25岁

运行结果预期:

Tom, 20岁
Jerry, 25岁

类方法常用于实现工厂方法,从不同数据源创建对象。


Python3 内置函数 Python3 内置函数


AI 思考中...

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /