classmethod和staticmethod
假设有这么一个 class
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
现在要把一个字符串 11-09-2012 作为变量,方法一:
string_date = '20-16-2017'
day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)
print date1.day
但是每次初始化一个 class 的 instance 都要重复操作一次。所以,方法二:
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
date2 = Date.from_string('20-06-2017')
print date2.day
staticmethod和classmethod类似,区别在于不接收变量。例如在 class 加入一个判断:
@staticmethod
def is_date_valid(date_as_string_for_check):
day, month, year = map(int, date_as_string_for_check.split('-'))
return day <= 31 and month <= 12 and year <= 3999
date2 = Date.from_string('20-06-2017')
is_date = Date.is_date_valid('20-06-2017')
print date2.day
print is_date
另外一个使用了 classmethod和staticmethod的例子:
class Employee:
num_of_emps = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amount = amount
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
import datetime
my_date = datetime.date(2016, 7, 11)
print(Employee.is_workday(my_date))
另外一个例子:
class Letter:
def __init__(self, pattern=None):
self.pattern = pattern
def __iter__(self):
yield from self.pattern
def __str__(self):
output = []
for blip in self:
if blip == '.':
output.append('dot')
else:
output.append('dash')
return '-'.join(output)
@classmethod
def from_string(cls, pattern_string):
# new_input_str = []
pattern_string = pattern_string.split('-')
for i, _ in enumerate(pattern_string):
if _ == 'dot':
pattern_string[i] = '.'
elif _ == 'dash':
pattern_string[i] = '_'
cls = cls(pattern_string)
return cls
# for _ in input_str:
# if _ == 'dot':
# new_input_str.append('.')
# elif _ == 'dash':
# new_input_str.append('_')
class S(Letter):
def __init__(self):
pattern = ['.', '.', '.']
super().__init__(pattern)
classmethod和staticmethod的更多相关文章
- python基础知识讲解——@classmethod和@staticmethod的作用
python基础知识讲解——@classmethod和@staticmethod的作用 在类的成员函数中,可以添加@classmethod和@staticmethod修饰符,这两者有一定的差异,简单来 ...
- Python中的classmethod与staticmethod
首先,这是一个经典的问题. 我们首先做一个比较: classmethod的第一个参数是cls,即调用的时候要把类传入 这意味着我们我们可以在classmethod里使用类的属性,而不是类的实例的属性( ...
- classmethod 和 staticmethod
我一般很少用到. Talk is cheap, show you the code. #!/usr/bin/env python # -*- coding: utf-8 -*- ########### ...
- 洗礼灵魂,修炼python(47)--巩固篇—定义类的方法之@classmethod,@staticmethod
定义类的方法,相信你会说,不就是在class语句下使用def () 就是定义类的方法了嘛,是的,这是定义的方法的一种,而且是最普通的方式 首先,我们已经知道有两种方式: 1.普通方法: 1)与类无关的 ...
- python基础-abstractmethod、__属性、property、setter、deleter、classmethod、staticmethod
python基础-abstractmethod.__属性.property.setter.deleter.classmethod.staticmethod
- 【python】Python 中的 classmethod 和 staticmethod
Python 中的 classmethod 和 staticmethod 有什么具体用途? 推荐地址:http://www.cnblogs.com/wangyongsong/p/6750454.htm ...
- python classmethod 和 staticmethod的区别
https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner 1. ...
- python的@classmethod和@staticmethod
本文是对StackOverflow上的一篇高赞回答的不完全翻译,原文链接:meaning-of-classmethod-and-staticmethod-for-beginner Python面向对象 ...
- python 封装,隐藏属性,绑定方法classmethod和staticmethod
[封装] 隐藏对象的属性和实现细节,仅对外提供公共访问方式. [好处] 1. 将变化隔离: 2. 便于使用: 3. 提高复用性: 4. 提高安全性: [封装原则] 1. 将不需要对外提供的内容都隐藏起 ...
- Fluent Python: Classmethod vs Staticmethod
Fluent Python一书9.4节比较了 Classmethod 和 Staticmethod 两个装饰器的区别: 给出的结论是一个非常有用(Classmethod), 一个不太有用(Static ...
随机推荐
- H3C F100-S-G2接口配置
网络环境简单一台F100-S-G2(192.168.1.197),一台S3600,三台服务器(同一网段192.168.1~3),实现互通. 其他都不用说了配置成同一网段地址就行,主要说一下F100配置 ...
- 数据库索引原理,及MySQL索引类型(转)
在数据库表中,对字段建立索引可以大大提高查询速度.假如我们创建了一个 mytable表: CREATE TABLE mytable( ID INT NOT NULL, username ) NOT N ...
- 搭建ELK和EFK
公司突然发下任务让我搭建elk和efk,于是做完之后写入了博客,生产环境下,亲测可用哦 搭建ELK 一共两台服务器,一个节点(logstash) 主服务器上 修改最大链接和最大打开的文件 1.临时修改 ...
- SQL Server 管理套件(SSMS)
SQL Server 管理套件(SSMS) 当您按照之前章节的步骤顺利安装完 SQL Server 2014 后,要做的第一件事就是需要打开 SQL Server 管理套件,并且要知道怎样去使用它. ...
- css实现文本溢出用...显示
文本溢出省略号显示,要实现这个必须 要有四个条件: 1.须有容器宽度:width:value 2.强制文本在一行内显示:white-space:nowrap: 3.溢出内容隐藏:overflow:hi ...
- dependency与dependencyManagement区别
在maven的pom文件中,有时候会见到dependencyManagement,它与denpendency有什么区别? 比方说,你在一个parent的pom里把你所需要的依赖包,版本号都写在depe ...
- centos系统下安装MySQL5.7.18
1.首先安装依赖包 yum install -y gcc gcc-c++ ncurses-devel perl openssl-devel 最最重要的是,不要忘了安装openssl-devel 2.安 ...
- (转)使用OpenGL显示图像(五)添加移动
添加移动 编写:jdneo - 原文:http://developer.android.com/training/graphics/opengl/motion.html 转:http://hukai. ...
- Hive HiveQL基础知识及常用语句总结
基础语句 CREATE DROP 建表.删表 建表 -------------------------------------- -- 1. 直接建表 ------------------------ ...
- Mysql全文索引的使用
前言 在MySQL 5.6版本以前,只有MyISAM存储引擎支持全文引擎.在5.6版本中,InnoDB加入了对全文索引的支持,但是不支持中文全文索引.在5.7.6版本,MySQL内置了ngram全文解 ...