Python中staticmethod和classmethod的作用与区别
作者:斜阳雨陌 发布时间:2022-03-12 21:30:00
标签:python,staticmethod,classmethod
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。
而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用。
这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
既然@staticmethod和@classmethod都可以直接类名.方法名()来调用,那他们有什么区别呢
从它们的使用上来看
@staticmethod不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。
如果在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
而@classmethod因为持有cls参数,可以来调用类的属性,类的方法,实例化对象等,避免硬编码。
要明白,什么是实例方法、静态方法和类方法:
class Demo(object):
def instance_method(self, your_para):
"""
this is an instance_method
you should call it like the follow:
a = Demo()
a.instance_method(your_para)
plus: in python, we denote 'cls' as latent para of Class
while 'self' as latent para of the instance of the Class
:param your_para:
:return:
"""
print("call instance_method and get:", your_para)
@classmethod
def class_method(cls, your_para):
"""
this is a class_method
you can call it like the follow:
method1:
a = Demo()
a.class_method(your_para)
method2:
Demo.class_method
plus: in python, we denote 'cls' as latent para of Class
while 'self' as latent para of the instance of the Class
:param your_para:
:return:
"""
print("call class_method and get:", your_para)
@staticmethod
def static_method(your_para):
"""
this is a static_method and you can call it like the
methods of class_method
:param your_para:
:return:
"""
print("call static_method and get:", your_para)
虽然类方法在调用的时候没有显式声明cls,但实际上类本身是作为隐含参数传入的。这就像实例方法在调用的时候也没有显式声明self,但实际上实例本身是作为隐含参数传入的。
对于静态函数,我们一般把与类无关也与实例无关的函数定义为静态函数。例如入口检查的函数就最好定义成静态函数。
类方法的妙处, 在继承中的作用:
class Fruit(object):
total = 0 # 这是一个类属性
@classmethod
def print_total(cls):
print('this is the ', cls, '.total:', cls.total, ' and its id: ', id(cls.total)) # cls是类本身,打印类属性total的值
print('this is the Fruit.total:', Fruit.total, 'and its id: ', id(Fruit.total))
print("=======================")
@classmethod
def set(cls, value):
cls.total = value
class Apple(Fruit):
pass
class Orange(Fruit):
pass
app1 = Apple()
app1.set(10)
app1.print_total()
Apple.print_total()
Fruit.set(2)
app1.print_total()
Fruit.print_total()
"""
output:
this is the <class '__main__.Apple'> .total: 10 and its id: 1355201264
this is the Fruit.total: 0 and its id: 1355200944
=======================
this is the <class '__main__.Apple'> .total: 10 and its id: 1355201264
this is the Fruit.total: 0 and its id: 1355200944
=======================
this is the <class '__main__.Apple'> .total: 10 and its id: 1355201264
this is the Fruit.total: 2 and its id: 1355201008
=======================
this is the <class '__main__.Fruit'> .total: 2 and its id: 1355201008
this is the Fruit.total: 2 and its id: 1355201008
=======================
"""
来源:https://blog.csdn.net/qq_15037231/article/details/77943109


猜你喜欢
- 目录互斥锁读写互斥锁先来看这样一段代码,所存在的问题:var wg sync.WaitGroupvar x int64func main()
- 前言:这个系列的专栏是为了保持 Python 手感而创建的,也可以用来学习 Python,因为存在知识跨越难度,所以先学习滚雪球系列为佳。二
- 我们经常会用到表格数据,在做表格的时候,一般都喜欢隔行变色,使表格表现数据的时候非常的清晰。如图,我设计的一个表格表现的样式:在网上找到一个
- import csvfor line in open("test.csv"):name,age,birthday = l
- 通过XSL转换XML文件 最近,我喜欢上了XML编程,但又苦于它的美观程度又不够,找了许多书才搞定。用XML好是蛮好,但它还是不太适合做显示
- 简介使用faker可以获取很多模拟数据,如:姓名、电话、地址、银行、汽车、条形码、公司、信用卡、email、user_agen等等学会使用这
- 目录一、变量、常量的区别二、变量1. Python中的变量不需要声明类型2. 用“=”号来给变量赋值3. 赋值4. 变量5. “=”6. P
- 1. watch 与 computed 的巧妙结合如上图,一个简单的列表页面。你可能会这么做: created(){ this.
- 在PyQt中没有直接提供左键双击的判断方法,需要自己实现,其思路主要如下所示:1、起动一个定时器,判断在指定的时间之内,点击次数
- 本文介绍MySQL查看数据库表容量大小的命令语句,提供完整查询语句及实例,方便大家学习使用。 1.查看所有数据库容量大小select tab
- 1.打开PyCharm,选择File--Settings2.依次选择Editor---Code Style-- File and Code
- 一、运算符 . [] () 属性存取及函数调用 delete new typeof + - ! 一元运算符 * / % 乘法,除法,取模 +
- 基于上一篇文章,这篇文章是关于使用coverage来实现代码覆盖的操作实例,源代码在上一篇已经给出相应链接。本篇文章字用来实现代码覆盖的源代
- javascript中要判断一个变量是否为array通常是比较困难的,因为var a = [];alert(t
- 前言对于专业的python程序员来说,python打包工具或许用得并不多。但是对于非专业人士来说,你给他写个python项目,要让他安装py
- 阻塞定义当来自应用程序的第一个连接控制锁而第二个连接需要相冲突的锁类型时,将发生阻塞。其结果是强制第二个连接等待,而在第一个连接上阻塞。不管
- 目录题目描述示例 1:示例 2:示例 3:单向构造(哈希表计数)双向构造(双指针)最后题目描述这是 LeetCode 上的 1743. 从相
- 从SQL Server2005开始提供了一种新的数据类型XML type,它允许用户将数据以XML文件的格式直接存储到数据表中。结合在ASP
- 设计原理从结构上来说,一个简单的图形界面,需要由界面组件、组件的事件 * (响应各类事件的逻辑)和具体的事件处理逻辑组成。界面实现的主要工作
- 这几天做了一个专题,放到服务器后发现从首页链接到专题页面正常,但是从专题页面跳转到首页就会出现乱码。很是蹊跷,专题页面和首页没有共同的文件,