假设有这么一个 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

但是每次初始化一个 classinstance 都要重复操作一次。所以,方法二:

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

staticmethodclassmethod类似,区别在于不接收变量。例如在 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

另外一个使用了 classmethodstaticmethod的例子:

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的更多相关文章

  1. python基础知识讲解——@classmethod和@staticmethod的作用

    python基础知识讲解——@classmethod和@staticmethod的作用 在类的成员函数中,可以添加@classmethod和@staticmethod修饰符,这两者有一定的差异,简单来 ...

  2. Python中的classmethod与staticmethod

    首先,这是一个经典的问题. 我们首先做一个比较: classmethod的第一个参数是cls,即调用的时候要把类传入 这意味着我们我们可以在classmethod里使用类的属性,而不是类的实例的属性( ...

  3. classmethod 和 staticmethod

    我一般很少用到. Talk is cheap, show you the code. #!/usr/bin/env python # -*- coding: utf-8 -*- ########### ...

  4. 洗礼灵魂,修炼python(47)--巩固篇—定义类的方法之@classmethod,@staticmethod

    定义类的方法,相信你会说,不就是在class语句下使用def () 就是定义类的方法了嘛,是的,这是定义的方法的一种,而且是最普通的方式 首先,我们已经知道有两种方式: 1.普通方法: 1)与类无关的 ...

  5. python基础-abstractmethod、__属性、property、setter、deleter、classmethod、staticmethod

    python基础-abstractmethod.__属性.property.setter.deleter.classmethod.staticmethod

  6. 【python】Python 中的 classmethod 和 staticmethod

    Python 中的 classmethod 和 staticmethod 有什么具体用途? 推荐地址:http://www.cnblogs.com/wangyongsong/p/6750454.htm ...

  7. python classmethod 和 staticmethod的区别

    https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner 1. ...

  8. python的@classmethod和@staticmethod

    本文是对StackOverflow上的一篇高赞回答的不完全翻译,原文链接:meaning-of-classmethod-and-staticmethod-for-beginner Python面向对象 ...

  9. python 封装,隐藏属性,绑定方法classmethod和staticmethod

    [封装] 隐藏对象的属性和实现细节,仅对外提供公共访问方式. [好处] 1. 将变化隔离: 2. 便于使用: 3. 提高复用性: 4. 提高安全性: [封装原则] 1. 将不需要对外提供的内容都隐藏起 ...

  10. Fluent Python: Classmethod vs Staticmethod

    Fluent Python一书9.4节比较了 Classmethod 和 Staticmethod 两个装饰器的区别: 给出的结论是一个非常有用(Classmethod), 一个不太有用(Static ...

随机推荐

  1. 深度探索C++对象模型第四章:函数语义学

    C++有三种类型的成员函数:static/nonstatic/virtual 一.成员的各种调用方式 C with class 只支持非静态成员函数(Nonstatic member function ...

  2. JVM内存模型及GC回收算法

    该篇博客主要对JVM内存模型以及GC回收算法以自己的理解和认识做以记录. 内存模型 GC垃圾回收 1.内存模型 从上图可以看出,JVM分为 方法区,虚拟机栈,本地方法栈,堆,计数器 5个区域.其中最为 ...

  3. hadoop 2.7 添加或删除datanode节点

    1.测试环境 ip 主机名 角色 10.124.147.22 hadoop1 namenode 10.124.147.23 hadoop2 namenode 10.124.147.32 hadoop3 ...

  4. Shell及其操作环境

    来源: 鸟哥的Linux私房菜第十章.認識與學習BASH Shell是什么?1分钟理解Shell的概念! ssh在本地调用远程主机上的命令,不登录远程主机shell 一.Shell Shell 是一个 ...

  5. Spring data jpa persistence .xml 配置文件

    <?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://j ...

  6. HTTP详解教程 / HTTP 响应头信息 HTTP 响应头信息

    HTTP请求头提供了关于请求,响应或者其他的发送实体的信息. 在本章节中我们将具体来介绍HTTP响应头信息.直线电机哪家好 应答头 说明 Allow 服务器支持哪些请求方法(如GET.POST等). ...

  7. 2019牛客多校第五场G-subsequence 1 DP

    G-subsequence 1 题意 给你两个字符串\(s.t\),问\(s\)中有多少个子序列能大于\(t\). 思路 令\(len1\)为\(s\)的子序列的长度,\(lent\)为\(t\)的长 ...

  8. Android代码学习--点击事件的几种写法

    由来:常规的写法参见<写一个apk>,每次点击按钮,按钮先查找文本框等元素,然后再操作,其实查找操作是很费时的操作,因此将该定义放到Activity的onCreate中:Oncreate只 ...

  9. JSHOP2

    JSHOP2是一个HTN(hierarchy task network)规划器,是SHOP2(simple hierarchy ordered planner )的java实现版本. SHOP2的官网 ...

  10. scala解析json —— json4s 解析json方法汇总

    使用json4s的框架,包括spark,flink 1.org.json4s 引入pom的方法 对于本地支持,引入以下依赖项添加到pom中 <dependency> <groupId ...