网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

python中cls函数,python cls函数

python 截取指定字符前后的所有字符的函数

可以参考下面的代码:

成都创新互联云计算的互联网服务提供商,拥有超过13年的服务器租用、重庆服务器托管、云服务器、网络空间、网站系统开发经验,已先后获得国家工业和信息化部颁发的互联网数据中心业务许可证。专业提供云主机、网络空间、域名与空间、VPS主机、云服务器、香港云服务器、免备案服务器等。

#!/usr/bin/python

# encoding: utf-8

# filename: baiduzhidao.py

ln = "4564612131856+654654654654"

print ln.split("+")

#~ Result:

#~ python -u "baiduzhidao.py"

#~ ['4564612131856', '654654654654']

#~ Exit code: 0    Time: 0.052

Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读、易维护,并且被大量用户所欢迎的、用途广泛的语言,设计者开发时总的指导思想是,对于一个特定的问题,只要有一种最好的方法来解决就好了。

Python本身被设计为可扩充的。并非所有的特性和功能都集成到语言核心。Python提供了丰富的API和工具,以便程序员能够轻松地使用C语言、C++、Cython来编写扩充模块。

Python是完全面向对象的语言。函数、模块、数字、字符串都是对象。并且完全支持继承、重载、派生、多继承,有益于增强源代码的复用性。

扩展资料:

python参考函数

vars(obj) 返回一个object的name space。用dictionary表示

locals() 返回一个局部name space,用dictionary表示

globals() 返回一个全局name space,用dictionary表示

type(obj) 查看一个obj的类型

isinstance(obj,cls) 查看obj是不是cls的instance

issubclass(subcls,supcls) 查看subcls是不是supcls的子类

参考资料来源:百度百科-Python (计算机程序设计语言)

Python中常见魔法方法介绍

魔法方法 (Magic Methods) 是Python中的内置函数,一般以双下划线开头和结尾,例如__ init__ 、 __del__ 等。之所以称之为魔法方法,是因为这些方法会在进行特定的操作时会自动被调用。

在Python中,可以通过dir()方法来查看某个对象的所有方法和属性,其中双下划线开头和结尾的就是该对象的魔法方法。以字符串对象为例:

可以看到字符串对象有 __add__ 方法,所以在Python中可以直接对字符串对象使用"+"操作,当Python识别到"+"操作时,就会调用该对象的 __add__ 方法。有需要时我们可以在自己的类中重写 __add__ 方法来完成自己想要的效果。

我们重写了 __add__ 方法,当Python识别"+"操作时,会自动调用重写后的 __add__ 方法。可以看到,魔法方法在类或对象的某些事件出发后会自动执行,如果希望根据自己的程序定制特殊功能的类,那么就需要对这些方法进行重写。使用魔法方法,我们可以非常方便地给类添加特殊的功能。

1、构造与初始化

__ new __ 、 __ init __ 这两个魔法方法常用于对类的初始化操作。上面我们创建a1 = A("hello")时,但首先调用的是 __ new __ ;初始化一个类分为两步:

a.调用该类的new方法,返回该类的实例对象

b.调用该类的init方法,对实例对象进行初始化。

__new__ (cls, *args, **kwargs)至少需要一个cls参数,代表传入的类。后面两个参数传递给 __ init __ 。在 __ new __ 可以决定是否继续调用 __ init __ 方法,只有当 __ new __ 返回了当前类cls的实例,才会接着调用 __ init __ 。结合 __ new __ 方法的特性,我们可以通过重写 __ new __ 方法实现Python的单例模式:

可以看到虽然创建了两个对象,但两个对象的地址相同。

2、控制属性访问这类魔法

方法主要对对象的属性进行访问、定义、修改时起作用。主要有:

__getattr__(self, name): 定义当用户试图获取一个属性时的行为。

__getattribute__(self, name):定义当该类的属性被访问时的行为(先调用该方法,查看是否存在该属性,若不存在,接着去调用getattr)。

__setattr__(self, name, value):定义当一个属性被设置时的行为。

当初始化属性时如self.a=a时或修改实例属性如ins.a=1时本质时调用魔法方法self. __ setattr __ (name,values);当实例访问某个属性如ins.a本质是调用魔法方法a. __ getattr __ (name)

3、容器类操作

有一些方法可以让我们自己定义自己的容器,就像Python内置的List,Tuple,Dict等等;容器分为可变容器和不可变容器。

如果自定义一个不可变容器的话,只能定义__ len__ 和__ getitem__ ;定义一个可变容器除了不可变容器的所有魔法方法,还需要定义__ setitem__ 和__ delitem__ ;如果容器可迭代。还需要定义__ iter __。

__len__(self):返回容器的长度

__getitem__(self,key):当需要执行self[key]的方式去调用容器中的对象,调用的是该方法

__setitem__(self,key,value):当需要执行self[key] = value时,调用的是该方法

__iter__(self):当容器可以执行 for x in container:,或者使用iter(container)时,需要定义该方法

下面举一个例子,实现一个容器,该容器有List的一般功能,同时增加一些其它功能如访问第一个元素,最后一个元素,记录每个元素被访问的次数等。

这类方法的使用场景主要在你需要定义一个满足需求的容器类数据结构时会用到,比如可以尝试自定义实现树结构、链表等数据结构(在collections中均已有),或者项目中需要定制的一些容器类型。

魔法方法在Python代码中能够简化代码,提高代码可读性,在常见的Python第三方库中可以看到很多对于魔法方法的运用。

因此当前这篇文章仅是抛砖引玉,真正的使用需要在开源的优秀源码中以及自身的工程实践中不断加深理解并合适应用。

python3的sympy

print(“字符串”),5/2和5//2的结果是不同的5/2为2.5,5//2为2.

python2需要导入from_future_import division执行普通的除法。

1/2和1//2的结果0.5和0.

%号为取模运算。

乘方运算为2**3,-2**3和-(2**3)是等价的。

from sympy import*导入库

x,y,z=symbols('x y z'),定义变量

init_printing(use_unicode=True)设置打印方式。

python的内部常量有pi,

函数simplify,simplify(sin(x)**2 + cos(x)**2)化简结果为1,

simplify((x**3 + x**2 - x - 1)/(x**2 + 2*x + 1))化简结果为x-1。化简伽马函数。simplify(gamma(x)/gamma(x - 2))得(x-2)(x-1)。

expand((x + 1)**2)展开多项式。

expand((x + 1)*(x - 2) - (x - 1)*x)

因式分解。factor(x**2*z + 4*x*y*z + 4*y**2*z)得到z*(x + 2*y)**2

from_future_import division

x,y,z,t=symbols('x y z t')定义变量,

k, m, n = symbols('k m n', integer=True)定义三个整数变量。

f, g, h = symbols('f g h', cls=Function)定义的类型为函数。

factor_list(x**2*z + 4*x*y*z + 4*y**2*z)得到一个列表,表示因式的幂,(1, [(z, 1), (x + 2*y, 2)])

expand((cos(x) + sin(x))**2)展开多项式。

expr = x*y + x - 3 + 2*x**2 - z*x**2 + x**3,collected_expr = collect(expr, x)将x合并。将x元素按阶次整合。

collected_expr.coeff(x, 2)直接取出变量collected_expr的x的二次幂的系数。

cancel()is more efficient thanfactor().

cancel((x**2 + 2*x + 1)/(x**2 + x))

,expr = (x*y**2 - 2*x*y*z + x*z**2 + y**2 - 2*y*z + z**2)/(x**2 - 1),cancel(expr)

expr = (4*x**3 + 21*x**2 + 10*x + 12)/(x**4 + 5*x**3 + 5*x**2 + 4*x),apart(expr)

asin(1)

trigsimp(sin(x)**2 + cos(x)**2)三角函数表达式化简,

trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4)

trigsimp(sin(x)*tan(x)/sec(x))

trigsimp(cosh(x)**2 + sinh(x)**2)双曲函数。

三角函数展开,expand_trig(sin(x + y)),acos(x),cos(acos(x)),expand_trig(tan(2*x))

x, y = symbols('x y', positive=True)正数,a, b = symbols('a b', real=True)实数,z, t, c = symbols('z t c')定义变量的方法。

sqrt(x) == x**Rational(1, 2)判断是否相等。

powsimp(x**a*x**b)幂函数的乘法,不同幂的乘法,必须先定义a和b。powsimp(x**a*y**a)相同幂的乘法。

powsimp(t**c*z**c),注意,powsimp()refuses to do the simplification if it is not valid.

powsimp(t**c*z**c, force=True)这样的话就可以得到化简过的式子。声明强制进行化简。

(z*t)**2,sqrt(x*y)

第一个展开expand_power_exp(x**(a + b)),expand_power_base((x*y)**a)展开,

expand_power_base((z*t)**c, force=True)强制展开。

powdenest((x**a)**b),powdenest((z**a)**b),powdenest((z**a)**b, force=True)

ln(x),x, y ,z= symbols('x y z', positive=True),n = symbols('n', real=True),

expand_log(log(x*y))展开为log(x) + log(y),但是python3没有。这是因为需要将x定义为positive。这是必须的,否则不会被展开。expand_log(log(x/y)),expand_log(log(x**n))

As withpowsimp()andpowdenest(),expand_log()has aforceoption that can be used to ignore assumptions。

expand_log(log(z**2), force=True),强制展开。

logcombine(log(x) + log(y)),logcombine(n*log(x)),logcombine(n*log(z), force=True)。

factorial(n)阶乘,binomial(n, k)等于c(n,k),gamma(z)伽马函数。

hyper([1, 2], [3], z),

tan(x).rewrite(sin)得到用正弦表示的正切。factorial(x).rewrite(gamma)用伽马函数重写阶乘。

expand_func(gamma(x + 3))得到,x*(x + 1)*(x + 2)*gamma(x),

hyperexpand(hyper([1, 1], [2], z)),

combsimp(factorial(n)/factorial(n - 3))化简,combsimp(binomial(n+1, k+1)/binomial(n, k))化简。combsimp(gamma(x)*gamma(1 - x))

自定义函数

def list_to_frac(l):

expr = Integer(0)

for i in reversed(l[1:]):

expr += i

expr = 1/expr

return l[0] + expr

list_to_frac([x, y, z])结果为x + 1/z,这个结果是错误的。

syms = symbols('a0:5'),定义syms,得到的结果为(a0, a1, a2, a3, a4)。

这样也可以a0, a1, a2, a3, a4 = syms, 可能是我的操作错误 。发现python和自动缩进有关,所以一定看好自动缩进的距离。list_to_frac([1, 2, 3, 4])结果为43/30。

使用cancel可以将生成的分式化简,frac = cancel(frac)化简为一个分数线的分式。

(a0*a1*a2*a3*a4 + a0*a1*a2 + a0*a1*a4 + a0*a3*a4 + a0 + a2*a3*a4 + a2 + a4)/(a1*a2*a3*a4 + a1*a2 + a1*a4 + a3*a4 + 1)

a0, a1, a2, a3, a4 = syms定义a0到a4,frac = apart(frac, a0)可将a0提出来。frac=1/(frac-a0)将a0去掉取倒。frac = apart(frac, a1)提出a1。

help("modules"),模块的含义,help("modules yourstr")模块中包含的字符串的意思。,

help("topics"),import os.path + help("os.path"),help("list"),help("open")

# -*- coding: UTF-8 -*-声明之后就可以在ide中使用中文注释。

定义

l = list(symbols('a0:5'))定义列表得到[a0, a1, a2, a3, a4]

fromsympyimport*

x,y,z=symbols('x y z')

init_printing(use_unicode=True)

diff(cos(x),x)求导。diff(exp(x**2), x),diff(x**4, x, x, x)和diff(x**4, x, 3)等价。

diff(expr, x, y, 2, z, 4)求出表达式的y的2阶,z的4阶,x的1阶导数。和diff(expr, x, y, y, z, 4)等价。expr.diff(x, y, y, z, 4)一步到位。deriv = Derivative(expr, x, y, y, z, 4)求偏导。但是不显示。之后用deriv.doit()即可显示

integrate(cos(x), x)积分。定积分integrate(exp(-x), (x, 0, oo))无穷大用2个oo表示。integrate(exp(-x**2-y**2),(x,-oo,oo),(y,-oo,oo))二重积分。print(expr)print的使用。

expr = Integral(log(x)**2, x),expr.doit()积分得到x*log(x)**2 - 2*x*log(x) + 2*x。

integ.doit()和integ = Integral((x**4 + x**2*exp(x) - x**2 - 2*x*exp(x) - 2*x -

exp(x))*exp(x)/((x - 1)**2*(x + 1)**2*(exp(x) + 1)), x)连用。

limit(sin(x)/x,x,0),not-a-number表示nan算不出来,limit(expr, x, oo),,expr = Limit((cos(x) - 1)/x, x, 0),expr.doit()连用。左右极限limit(1/x, x, 0, '+'),limit(1/x, x, 0, '-')。。

Series Expansion级数展开。expr = exp(sin(x)),expr.series(x, 0, 4)得到1 + x + x**2/2 + O(x**4),,x*O(1)得到O(x),,expr.series(x, 0, 4).removeO()将无穷小移除。exp(x-6).series(x,x0=6),,得到

-5 + (x - 6)**2/2 + (x - 6)**3/6 + (x - 6)**4/24 + (x - 6)**5/120 + x + O((x - 6)**6, (x, 6))最高到5阶。

f=Function('f')定义函数变量和h=Symbol('h')和d2fdx2=f(x).diff(x,2)求2阶,,as_finite_diff(dfdx)函数和as_finite_diff(d2fdx2,[-3*h,-h,2*h]),,x_list=[-3,1,2]和y_list=symbols('a b c')和apply_finite_diff(1,x_list,y_list,0)。

Eq(x, y),,solveset(Eq(x**2, 1), x)解出来x,当二式相等。和solveset(Eq(x**2 - 1, 0), x)等价。solveset(x**2 - 1, x)

solveset(x**2 - x, x)解,solveset(x - x, x, domain=S.Reals)解出来定义域。solveset(exp(x), x)    # No solution exists解出EmptySet()表示空集。

等式形式linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))和矩阵法linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))得到{(-y - 1, y, 2)}

A*x = b 形式,M=Matrix(((1,1,1,1),(1,1,2,3))),system=A,b=M[:,:-1],M[:,-1],linsolve(system,x,y,z),,solveset(x**3 - 6*x**2 + 9*x, x)解多项式。roots(x**3 - 6*x**2 + 9*x, x),得出,{3: 2, 0: 1},有2个3的重根,1个0根。solve([x*y - 1, x - 2], x, y)解出坐标。

f, g = symbols('f g', cls=Function)函数的定义,解微分方程diffeq = Eq(f(x).diff(x, x) - 2*f(x).diff(x) + f(x), sin(x))再和dsolve(diffeq,f(x))结合。得到Eq(f(x), (C1 + C2*x)*exp(x) + cos(x)/2),dsolve(f(x).diff(x)*(1 - sin(f(x))), f(x))解出来Eq(f(x) + cos(f(x)), C1),,

Matrix([[1,-1],[3,4],[0,2]]),,Matrix([1, 2, 3])列表示。M=Matrix([[1,2,3],[3,2,1]])

N=Matrix([0,1,1])

M*N符合矩阵的乘法。M.shape显示矩阵的行列数。

M.row(0)获取M的第0行。M.col(-1)获取倒数第一列。

M.col_del(0)删掉第1列。M.row_del(1)删除第二行,序列是从0开始的。M = M.row_insert(1, Matrix([[0, 4]]))插入第二行,,M = M.col_insert(0, Matrix([1, -2]))插入第一列。

M+N矩阵相加,M*N,3*M,M**2,M**-1,N**-1表示求逆。M.T求转置。

eye(3)单位。zeros(2, 3),0矩阵,ones(3, 2)全1,diag(1, 2, 3)对角矩阵。diag(-1, ones(2, 2), Matrix([5, 7, 5]))生成Matrix([

[-1, 0, 0, 0],

[ 0, 1, 1, 0],

[ 0, 1, 1, 0],

[ 0, 0, 0, 5],

[ 0, 0, 0, 7],

[ 0, 0, 0, 5]])矩阵。

Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])

一行一行显示,,M.det()求行列式。M.rref()矩阵化简。得到结果为Matrix([

[1, 0,  1,  3],

[0, 1, 2/3, 1/3],

[0, 0,  0,  0]]), [0, 1])。

M = Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]]),M.nullspace()

Columnspace

M.columnspace()和M = Matrix([[1, 2, 3, 0, 0], [4, 10, 0, 0, 1]])

M = Matrix([[3, -2,  4, -2], [5,  3, -3, -2], [5, -2,  2, -2], [5, -2, -3,  3]])和M.eigenvals()得到{3: 1, -2: 1, 5: 2},,This means thatMhas eigenvalues -2, 3, and 5, and that the eigenvalues -2 and 3 have algebraic multiplicity 1 and that the eigenvalue 5 has algebraic multiplicity 2.

P, D = M.diagonalize(),P得Matrix([

[0, 1, 1,  0],

[1, 1, 1, -1],

[1, 1, 1,  0],

[1, 1, 0,  1]]),,D为Matrix([

[-2, 0, 0, 0],

[ 0, 3, 0, 0],

[ 0, 0, 5, 0],

[ 0, 0, 0, 5]])

P*D*P**-1 == M返回为True。lamda = symbols('lamda')。

lamda = symbols('lamda')定义变量,p = M.charpoly(lamda)和factor(p)

expr = x**2 + x*y,srepr(expr)可以将表达式说明计算法则,"Add(Pow(Symbol('x'), Integer(2)), Mul(Symbol('x'), Symbol('y')))"。。

x = symbols('x')和x = Symbol('x')是一样的。srepr(x**2)得到"Pow(Symbol('x'), Integer(2))"。Pow(x, 2)和Mul(x, y)得到x**2。x*y

type(2)得到class 'int',type(sympify(2))得到class 'sympy.core.numbers.Integer'..srepr(x*y)得到"Mul(Symbol('x'), Symbol('y'))"。。。

Add(Pow(x, 2), Mul(x, y))得到"Add(Mul(Integer(-1), Pow(Symbol('x'), Integer(2))), Mul(Rational(1, 2), sin(Mul(Symbol('x'), Symbol('y')))), Pow(Symbol('y'), Integer(-1)))"。。Pow函数为幂次。

expr = Add(x, x),expr.func。。Integer(2).func,class 'sympy.core.numbers.Integer',,Integer(0).func和Integer(-1).func,,,expr = 3*y**2*x和expr.func得到class 'sympy.core.mul.Mul',,expr.args将表达式分解为得到(3, x, y**2),,expr.func(*expr.args)合并。expr == expr.func(*expr.args)返回True。expr.args[2]得到y**2,expr.args[1]得到x,expr.args[0]得到3.。

expr.args[2].args得到(y, 2)。。y.args得到空括号。Integer(2).args得到空括号。

from sympy import *

E**(I*pi)+1,可以看出,I和E,pi已将在sympy内已定义。

x=Symbol('x'),,expand( E**(I*x) )不能展开,expand(exp(I*x),complex=True)可以展开,得到I*exp(-im(x))*sin(re(x)) + exp(-im(x))*cos(re(x)),,x=Symbol("x",real=True)将x定义为实数。再展开expand(exp(I*x),complex=True)得到。I*sin(x) + cos(x)。。

tmp = series(exp(I*x), x, 0, 10)和pprint(tmp)打印出来可读性好,print(tmp)可读性不好。。pprint将公式用更好看的格式打印出来,,pprint( series( cos(x), x, 0, 10) )

integrate(x*sin(x), x),,定积分integrate(x*sin(x), (x, 0, 2*pi))。。

用双重积分求解球的体积。

x, y, r = symbols('x,y,r')和2 * integrate(sqrt(r*r-x**2), (x, -r, r))计算球的体积。计算不来,是因为sympy不知道r是大于0的。r = symbols('r', positive=True)这样定义r即可。circle_area=2*integrate(sqrt(r**2-x**2),(x,-r,r))得到。circle_area=circle_area.subs(r,sqrt(r**2-x**2))将r替换。

integrate(circle_area,(x,-r,r))再积分即可。

expression.sub([(x,y),(y,x)])又换到原来的状况了。

expression.subs(x, y),,将算式中的x替换成y。。

expression.subs({x:y,u:v}) : 使用字典进行多次替换。。

expression.subs([(x,y),(u,v)]) : 使用列表进行多次替换。。

python中ls【】【】是什么意思?

【CSDN 编者按】Python 风头正盛,未来一段时间内想必也会是热门编程语言之一。因此,熟练掌握 Python 对开发者来说极其重要,说不定能给作为开发者的你带来意想不到的财富。

作者 | Sebastian Opałczyński

编译 | 弯月 责编 | 张文

出品 | CSDN(ID:CSDNnews)

在本文中,我们来看一看日常工作中经常使用的一些 Python 小技巧。

集合

开发人员常常忘记 Python 也有集合数据类型,大家都喜欢使用列表处理一切。

集合(set)是什么?简单来说就是:集合是一组无序事物的汇集,不包含重复元素。

如果你熟练掌握集合及其逻辑,那么很多问题都可以迎刃而解。举个例子,如何获取一个单词中出现的字母?

myword = "NanananaBatman"set(myword){'N', 'm', 'n', 'B', 'a', 't'}

就这么简单,问题解决了,这个例子就来自 Python 的官方文档,大可不必过于惊讶。

再举一个例子,如何获取一个列表的各个元素,且不重复?

# first you can easily change set to list and other way aroundmylist = ["a", "b", "c","c"]# let's make a set out of itmyset = set(mylist)# myset will be:{'a', 'b', 'c'}# and, it's already iterable so you can do:for element in myset:print(element)# but you can also convert it to list again:mynewlist = list(myset)# and mynewlist will be:['a', 'b', 'c']

我们可以看到,“c”元素不再重复出现了。只有一个地方你需要注意,mylist 与 mynewlist 之间的元素顺序可能会有所不同:

mylist = ["c", "c", "a","b"]mynewlist = list(set(mylist))# mynewlist is:['a', 'b', 'c']

可以看出,两个列表的元素顺序不同。

下面,我们来进一步深入。

假设某些实体之间有一对多的关系,举个更加具体的例子:用户与权限。通常,一个用户可以拥有多个权限。现在假设某人想要修改多个权限,即同时添加和删除某些权限,应当如何解决这个问题?

# this is the set of permissions before change;original_permission_set = {"is_admin","can_post_entry", "can_edit_entry", "can_view_settings"}# this is new set of permissions;new_permission_set = {"can_edit_settings","is_member", "can_view_entry", "can_edit_entry"}# now permissions to add will be:new_permission_set.difference(original_permission_set)# which will result:{'can_edit_settings', 'can_view_entry', 'is_member'}# As you can see can_edit_entry is in both sets; so we do notneed# to worry about handling it# now permissions to remove will be:original_permission_set.difference(new_permission_set)# which will result:{'is_admin', 'can_view_settings', 'can_post_entry'}# and basically it's also true; we switched admin to member, andadd# more permission on settings; and removed the post_entrypermission

总的来说,不要害怕使用集合,它们能帮助你解决很多问题,更多详情,请参考 Python 官方文档。

日历

当开发与日期和时间有关的功能时,有些信息可能非常重要,比如某一年的这个月有多少天。这个问题看似简单,但是我相信日期和时间是一个非常有难度的话题,而且我觉得日历的实现问题非常多,简直就是噩梦,因为你需要考虑大量的极端情况。

那么,究竟如何才能找出某个月有多少天呢?

import calendarcalendar.monthrange(2020, 12)# will result:(1, 31)# BUT! you need to be careful here, why? Let's read thedocumentation:help(calendar.monthrange)# Help on function monthrange in module calendar:# monthrange(year, month)# Return weekday (0-6~ Mon-Sun) and number of days (28-31) for# year, month.# As you can see the first value returned in tuple is a weekday,# not the number of the first day for a given month; let's try# to get the same for 2021calendar.monthrange(2021, 12)(2, 31)# So this basically means that the first day of December 2021 isWed# and the last day of December 2021 is 31 (which is obvious,cause# December always has 31 days)# let's play with Februarycalendar.monthrange(2021, 2)(0, 28)calendar.monthrange(2022, 2)(1, 28)calendar.monthrange(2023, 2)(2, 28)calendar.monthrange(2024, 2)(3, 29)calendar.monthrange(2025, 2)(5, 28)# as you can see it handled nicely the leap year;

某个月的第一天当然非常简单,就是 1 号。但是,“某个月的第一天是周X”,如何使用这条信息呢?你可以很容易地查到某一天是周几:

calendar.monthrange(2024, 2)(3, 29)# means that February 2024 starts on Thursday# let's define simple helper:weekdays = ["Monday", "Tuesday","Wednesday", "Thursday", "Friday","Saturday", "Sunday"]# now we can do something like:weekdays[3]# will result in:'Thursday'# now simple math to tell what day is 15th of February 2020:offset = 3 # it's thefirst value from monthrangefor day in range(1, 29):print(day,weekdays[(day + offset - 1) % 7])1 Thursday2 Friday3 Saturday4 Sunday...18 Sunday19 Monday20 Tuesday21 Wednesday22 Thursday23 Friday24 Saturday...28 Wednesday29 Thursday# which basically makes sense;

也许这段代码不适合直接用于生产,因为你可以使用 datetime 更容易地查找星期:

from datetime import datetimemydate = datetime(2024, 2, 15)datetime.weekday(mydate)# will result:3# or:datetime.strftime(mydate, "%A")'Thursday'

总的来说,日历模块有很多有意思的地方,值得慢慢学习:

# checking if year is leap:calendar.isleap(2021) #Falsecalendar.isleap(2024) #True# or checking how many days will be leap days for given yearspan:calendar.leapdays(2021, 2026) # 1calendar.leapdays(2020, 2026) # 2# read the help here, as range is: [y1, y2), meaning that second# year is not included;calendar.leapdays(2020, 2024) # 1

枚举有第二个参数

是的,枚举有第二个参数,可能很多有经验的开发人员都不知道。下面我们来看一个例子:

mylist = ['a', 'b', 'd', 'c', 'g', 'e']for i, item in enumerate(mylist):print(i, item)# Will give:0 a1 b2 d3 c4 g5 e# but, you can add a start for enumeration:for i, item in enumerate(mylist, 16):print(i, item)# and now you will get:16 a17 b18 d19 c20 g21 e

第二个参数可以指定枚举开始的地方,比如上述代码中的 enumerate(mylist,16)。如果你需要处理偏移量,则可以考虑这个参数。

if-else 逻辑

你经常需要根据不同的条件,处理不同的逻辑,经验不足的开发人员可能会编写出类似下面的代码:

OPEN = 1IN_PROGRESS = 2CLOSED = 3def handle_open_status():print('Handling openstatus')def handle_in_progress_status():print('Handling inprogress status')def handle_closed_status():print('Handling closedstatus')def handle_status_change(status):if status == OPEN:handle_open_status()elif status ==IN_PROGRESS:handle_in_progress_status()elif status == CLOSED:handle_closed_status()handle_status_change(1) #Handling open statushandle_status_change(2) #Handling in progress statushandle_status_change(3) #Handling closed status

虽然这段代码看上去也没有那么糟,但是如果有 20 多个条件呢?

那么,究竟应该怎样处理呢?

from enum import IntEnumclass StatusE(IntEnum):OPEN = 1IN_PROGRESS = 2CLOSED = 3def handle_open_status():print('Handling openstatus')def handle_in_progress_status():print('Handling inprogress status')def handle_closed_status():print('Handling closedstatus')handlers = {StatusE.OPEN.value:handle_open_status,StatusE.IN_PROGRESS.value: handle_in_progress_status,StatusE.CLOSED.value:handle_closed_status}def handle_status_change(status):if status not inhandlers:raiseException(f'No handler found for status: {status}')handler =handlers[status]handler()handle_status_change(StatusE.OPEN.value) # Handling open statushandle_status_change(StatusE.IN_PROGRESS.value) # Handling in progress statushandle_status_change(StatusE.CLOSED.value) # Handling closed statushandle_status_change(4) #Will raise the exception

在 Python 中这种模式很常见,它可以让代码看起来更加整洁,尤其是当方法非常庞大,而且需要处理大量条件时。

enum 模块

enum 模块提供了一系列处理枚举的工具函数,最有意思的是 Enum 和 IntEnum。我们来看个例子:

from enum import Enum, IntEnum, Flag, IntFlagclass MyEnum(Enum):FIRST ="first"SECOND ="second"THIRD ="third"class MyIntEnum(IntEnum):ONE = 1TWO = 2THREE = 3# Now we can do things like:MyEnum.FIRST ## it has value and name attributes, which are handy:MyEnum.FIRST.value #'first'MyEnum.FIRST.name #'FIRST'# additionally we can do things like:MyEnum('first') #, get enum by valueMyEnum['FIRST'] #, get enum by name

使用 IntEnum 编写的代码也差不多,但是有几个不同之处:

MyEnum.FIRST == "first" # False# butMyIntEnum.ONE == 1 # True# to make first example to work:MyEnum.FIRST.value == "first" # True

在中等规模的代码库中,enum 模块在管理常量方面可以提供很大的帮助。

enum 的本地化可能有点棘手,但也可以实现,我用django快速演示一下:

from enum import Enumfrom django.utils.translation import gettext_lazy as _class MyEnum(Enum):FIRST ="first"SECOND ="second"THIRD ="third"@classmethoddef choices(cls):return [(cls.FIRST.value, _('first')),(cls.SECOND.value, _('second')),(cls.THIRD.value, _('third'))# And later in eg. model definiton:some_field = models.CharField(max_length=10,choices=MyEnum.choices())

iPython

iPython 就是交互式 Python,它是一个交互式的命令行 shell,有点像 Python 解释器。

首先,你需要安装 iPython:

pip install ipython

接下来,你只需要在输入命令的时候,将 Python 换成 ipython:

# you should see something like this after you start:Python 3.8.5 (default, Jul 28 2020, 12:59:40)Type 'copyright', 'credits' or 'license' for more informationIPython 7.18.1 -- An enhanced Interactive Python. Type '?' forhelp.In [1]:

ipython 支持很多系统命令,比如 ls 或 cat,tab 键可以显示提示,而且你还可以使用上下键查找前面用过的命令。更多具体信息,请参见官方文档。

参考链接:

python 用clss怎么复制数字或者有什么方法定位

首先需要用open()函数打开文件,然后调用文件指针的readlines()函数,可以将文件的全部内容读入到一个列表当中,列表的每一个元素对应于文件的每一行,如果希望获取文件第k行的内容,只需要对列表索引第k-1个元素即可,因为Python是从0开始计数的。

示例代码如下:

f = open('meelo.txt')data = f.readlines()# 打印第4行的内容print(data[3])

示例代码中,打印了文件第4行的内容。


本文名称:python中cls函数,python cls函数
网站网址:http://bjjierui.cn/article/dssicod.html

其他资讯