Python - 静态方法@staticmethod和类方法classmethod
传送门
静态方法@staticmethod
- 记得在Fluent Python中大神讲过@staticmethod和普通的函数没什么两样;但是在以下的例子中可以看到,@staticmethod意义在于,这个静态方法和这个类是相关的(虽然这个类的实例对象能调用),但是一般这样设计是给类调用的。
例子: 我们定义一个“三角形”类,通过传入三条边长来构造三角形,并提供计算周长和面积的方法,但是传入的三条边长未必能构造出三角形对象,因此我们可以先写一个方法来验证三条边长是否可以构成三角形,**这个方法很显然就不是对象方法**,因为在调用这个方法时三角形对象尚未创建出来(因为都不知道三条边能不能构成三角形),所以**这个方法是属于三角形类而并不属于三角形对象的**。我们可以使用静态方法来解决这类问题,代码如下所示。
from math import sqrt
class Triangle(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
@staticmethod
def is_valid(a, b, c):
return a + b > c and b + c > a and a + c > b
# 求周长
def perimeter(self):
return self._a + self._b + self._c
# 求面积
def area(self):
# 海伦公式
half = self.perimeter() / 2
return sqrt(half * (half - self._a) *
(half - self._b) * (half - self._c))
def main():
a, b, c = 3, 4, 5
# 静态方法和类方法都是通过给类发消息来调用的
if Triangle.is_valid(a, b, c):
t = Triangle(a, b, c)
print(t.perimeter())
# 也可以通过给类发消息来调用对象方法但是要传入接收消息的对象作为参数
# print(Triangle.perimeter(t))
print(t.area())
# print(Triangle.area(t))
else:
print('无法构成三角形.')
if __name__ == '__main__':
main()
类方法@classmethod
- 和静态方法比较类似,Python还可以在类中定义类方法,类方法的第一个参数约定名(convention)为cls,它代表的是当前类相关的信息的对象(类本身也是一个对象,有的地方也称之为类的元数据对象),通过这个参数我们可以获取和类相关的信息并且可以创建出类的对象(在@classmethod修饰的函数中return cls()),代码如下所示。
from time import time, localtime, sleep
class Clock(object):
"""数字时钟"""
def __init__(self, hour=0, minute=0, second=0):
self._hour = hour
self._minute = minute
self._second = second
@classmethod
def now(cls):
current_time = localtime(time())
return cls(current_time.tm_hour, current_time.tm_min, current_time.tm_sec)
def run(self):
"""走字"""
self._second += 1
if self._second == 60:
self._second = 0
self._minute += 1
if self._minute == 60:
self._minute = 0
self._hour += 1
if self._hour == 24:
self._hour = 0
def show(self):
"""显示时间"""
return '%02d:%02d:%02d' % \
(self._hour, self._minute, self._second)
def main():
# 通过类方法创建对象并获取系统时间
clock = Clock.now()
while True:
print(clock.show())
sleep(1)
clock.run()
if __name__ == '__main__':
main()
@staticmethod 和 @classmethod
class Demo():
@classmethod
def klassmeth(cls, *args):
return args
@staticmethod
def statmeth(*args):
return args
# 不加cls,退化成@staticmethod
print(Demo.klassmeth()) # ()
print(Demo.klassmeth('spam')) # ()
print(Demo.klassmeth(Demo,)) # (<class '__main__.Demo'>,)
print(Demo.klassmeth(Demo, 'spam')) # (<class '__main__.Demo'>, 'spam')
print(Demo.statmeth()) # ()
print(Demo.statmeth('spam')) # ('spam',)
Python - 静态方法@staticmethod和类方法classmethod的更多相关文章
- 静态方法staticmethod和类方法classmethod
静态方法staticmethod和类方法classmethod 一.类方法classmethod 把一个方法变成一个类中的方法,这个方法可以直接利用类来调用,不需要依托任何的对象,即不需要实例化也可以 ...
- python-静态方法staticmethod、类方法classmethod、属性方法property
Python的方法主要有3个,即静态方法(staticmethod),类方法(classmethod)和实例方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def ...
- python中静态方法(@staticmethod)和类方法(@classmethod)的区别
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法. 而使用@staticmethod或@classmethod,就可以不需要实例化,直接类名.方法名()来调用. 这有利于组织代码,把某些应 ...
- 【面试必问】python实例方法、类方法@classmethod、静态方法@staticmethod和属性方法@property区别
[面试必问]python实例方法.类方法@classmethod.静态方法@staticmethod和属性方法@property区别 1.#类方法@classmethod,只能访问类变量,不能访问实例 ...
- Python的3个方法:静态方法(staticmethod),类方法(classmethod)和实例方法
Python的方法主要有3个,即静态方法(staticmethod),类方法(classmethod)和实例方法,如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
- Python静态方法(staticmethod)和类方法(classmthod)
Python静态方法(staticmethod)和类方法(classmthod)翻了翻之前的笔记,也刚好看到一篇不错的blog,关于静态方法和类方法的,方便以后查阅,就写在这里了,废话不多说,直接上代 ...
- python类方法@classmethod与@staticmethod
目录 python类方法@classmethod与@staticmethod 一.@classmethod 介绍 语法 举例 二.@staticmethod 介绍 语法 举例 python类方法@cl ...
- python 静态方法、类方法(二)
<Python静态方法.类方法>一文中曾用在类之外生成函数的方式,来计算类的实例的个数.本文将探讨用静态方法和类方法来实现此功能. 一使用静态方法统计实例 例1.static.py # - ...
- python中@staticmethod、@classmethod和实例方法
1.形式上的异同点: 在形式上,Python中:实例方法必须有self,类方法用@classmethod装饰必须有cls,静态方法用@staticmethod装饰不必加cls或self,如下代码所示: ...
随机推荐
- spring boot 2 集成JWT实现api接口认证
JSON Web Token(JWT)是目前流行的跨域身份验证解决方案.官网:https://jwt.io/本文使用spring boot 2 集成JWT实现api接口验证. 一.JWT的数据结构 J ...
- java基础之 开发环境配置
一.Window 第一步:下载JDK 首先,我们需要下载java开发工具包JDK,下载地址:http://www.oracle.com/technetwork/java/javase/download ...
- js -- 正则表达式集合
在做项目中,有时需要进行正则验证,但我又不太会正则表达式. 在一次又一次的寻找正则表达式的过程中,我最后总结了一个用于验证的函数,把我们常用的正则写在方法里,就不用每次都去网上找了. 可以根据需求进行 ...
- python面试的100题(3)
3.输入日期, 判断这一天是这一年的第几天? import datetime def dayofyear(): year = input("请输入年份: ") month = in ...
- httpclient发送请求的几种方式
package asi; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; ...
- crontab实践
1.crontab概要 2.crontab使用 3.关键配置信息 3.1如何配置定时任务 4.注意事项 参考 https://www.cnblogs.com/keithtt/p/6946498.htm ...
- 快速上手leetcode动态规划题
快速上手leetcode动态规划题 我现在是初学的状态,在此来记录我的刷题过程,便于以后复习巩固. 我leetcode从动态规划开始刷,语言用的java. 一.了解动态规划 我上网查了一下动态规划,了 ...
- Jquery获取html参数, jquery.params.js 获取参数
================================ ©Copyright 蕃薯耀 2019年12月31日 http://fanshuyao.iteye.com/ /** * 使用:$.q ...
- DataGridView单元格显示密码
DataGridView单元格显示密码 private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormatt ...
- python+tkinter+动画图片+爬虫(查询天气)的GUI图形界面设计
1.完整代码: import time import urllib.request #发送网络请求,获取数据 import gzip #压缩和解压缩模块 import json #解析获得的数据 fr ...