首页 后端开发 Python教程 Python 函数 类 语法糖

Python 函数 类 语法糖

Nov 22, 2016 pm 03:56 PM
python

Python 语法糖

\,换行连接

s = ''
s += 'a' + \
     'b' + \
     'c'
n = 1 + 2 + \
3
# 6
登录后复制

while,for 循环外的 else

如果 while 循环正常结束(没有break退出)就会执行else。

num = [1,2,3,4]
mark = 0while mark < len(num):
    n = num[mark]    if n % 2 == 0:   
     print(n)        # break
    mark += 1else: print("done")
登录后复制

zip() 并行迭代

a = [1,2,3]
b = [&#39;one&#39;,&#39;two&#39;,&#39;three&#39;]
list(zip(a,b))
# [(1, &#39;one&#39;), (2, &#39;two&#39;), (3, &#39;three&#39;)]
登录后复制

列表推导式

x = [num for num in range(6)]
# [0, 1, 2, 3, 4, 5]
y = [num for num in range(6) if num % 2 == 0]
# [0, 2, 4]

# 多层嵌套
rows = range(1,4)
cols = range(1,3)
for i in rows:
    for j in cols:
        print(i,j)
# 同
rows = range(1,4)
cols = range(1,3)
x = [(i,j) for i in rows for j in cols]
登录后复制

字典推导式

{ key_exp : value_exp fro expression in iterable }

#查询每个字母出现的次数。
strs = &#39;Hello World&#39;
s = { k : strs.count(k) for k in set(strs) }
登录后复制

集合推导式

{expression for expression in iterable }

元组没有推导式

本以为元组推导式是列表推导式改成括号,后来发现那个 生成器推导式。

生成器推导式

>>> num = ( x for x in range(5) )>>> num
...:<generator object <genexpr> at 0x7f50926758e0>
登录后复制

函数

函数关键字参数,默认参数值

def do(a=0,b,c)
    return (a,b,c)

do(a=1,b=3,c=2)
登录后复制

函数默认参数值在函数定义时已经计算出来,而不是在程序运行时。
列表字典等可变数据类型不可以作为默认参数值。

def buygy(arg, result=[]):
    result.append(arg)
    print(result)
登录后复制

changed:

def nobuygy(arg, result=None):
    if result == None:
        result = []
    result.append(arg)
    print(result)
# or
def nobuygy2(arg):
    result = []
    result.append(arg)
    print(result)
登录后复制

*args 收集位置参数

def do(*args):
    print(args)
do(1,2,3)
(1,2,3,&#39;d&#39;)
登录后复制

**kwargs 收集关键字参数

def do(**kwargs):
  print(kwargs)
do(a=1,b=2,c=&#39;la&#39;)
# {&#39;c&#39;: &#39;la&#39;, &#39;a&#39;: 1, &#39;b&#39;: 2}
登录后复制

lamba 匿名函数

a = lambda x: x*x
a(4)
# 16
登录后复制

生成器

生成器是用来创建Python序列的一个对象。可以用它迭代序列而不需要在内存中创建和存储整个序列。
通常,生成器是为迭代器产生数据的。

生成器函数函数和普通函数类似,返回值使用 yield 而不是 return 。

def my_range(first=0,last=10,step=1):
    number = first
    while number < last:
        yield number
        number += step

>>> my_range()
... <generator object my_range at 0x7f02ea0a2bf8>
登录后复制

装饰器

有时需要在不改变源代码的情况下修改已经存在的函数。
装饰器实质上是一个函数,它把函数作为参数输入到另一个函数。 举个栗子:

# 一个装饰器
def document_it(func):
    def new_function(*args, **kwargs):
        print("Runing function: ", func.__name__)
        print("Positional arguments: ", args)
        print("Keyword arguments: ", kwargs)
        result = func(*args, **kwargs)
        print("Result: " ,result)
        return result
    return new_function

# 人工赋值
def add_ints(a, b):
    return a + b

cooler_add_ints = document_it(add_ints) #人工对装饰器赋值
cooler_add_ints(3,5)

# 函数器前加装饰器名字
@document_it
def add_ints(a, b):
    return a + b
登录后复制

可以使用多个装饰器,多个装饰由内向外向外顺序执行。

命名空间和作用域

a = 1234
def test():
    print("a = ",a) # True
####
a = 1234
def test():
    a = a -1    #False
    print("a = ",a)
登录后复制

可以使用全局变量 global a 。

a = 1234
def test():
    global a
    a = a -1    #True
    print("a = ",a)
登录后复制

Python 提供了两个获取命名空间内容的函数 local() global()

_ 和 __

Python 保留用法。 举个栗子:

def amazing():
    &#39;&#39;&#39;This is the amazing.
    Hello
    world&#39;&#39;&#39;
    print("The function named: ", amazing.__name__)
    print("The function docstring is: \n", amazing.__doc__)
登录后复制

异常处理,try...except

只有错误发生时才执行的代码。 举个栗子:

>>> l = [1,2,3]
>>> index = 5
>>> l[index]
Traceback (most recent call last):
  File "<stdin>", line 1, in 
  <module>IndexError: list index out of range
登录后复制

再试下:

>>> l = [1,2,3]
>>> index = 5
>>> try:
...     l[index]
... except:
...     print("Error: need a position between 0 and", len(l)-1, ", But got", index)
...
Error: need a position between 0 and 2 , But got 5
登录后复制

没有自定异常类型使用任何错误。

获取异常对象,except exceptiontype as name

hort_list = [1,2,3]while 1:
    value = input("Position [q to quit]? ")    if value == &#39;q&#39;:        break
    try:
        position = int(value)
        print(short_list[position])    except IndexError as err:
        print("Bad index: ", position)    except Exception as other:
        print("Something else broke: ", other)
登录后复制

自定义异常

异常是一个类。类 Exception 的子类。

class UppercaseException(Exception):
    pass

words = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;AA&#39;]
for i in words:
    if i.isupper():
        raise UppercaseException(i)
# error
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
__main__.UppercaseException: AA
登录后复制

命令行参数

命令行参数

python文件:

import sys
print(sys.argv)
登录后复制

PPrint()友好输出

与print()用法相同,输出结果像是列表字典时会不同。

子类super()调用父类方法

举个栗子:

class Person():
    def __init__(self, name):
        self.name = nameclass email(Person):
    def __init__(self, name, email):
        super().__init__(name)
        self.email = email

a = email(&#39;me&#39;, &#39;me@me.me&#39;)>>> a.name... &#39;me&#39;>>> a.email... &#39;me@me.me&#39;
登录后复制

self.__name 保护私有特性

class Person():
    def __init__(self, name):
        self.__name = name
a = Person(&#39;me&#39;)>>> a.name... AttributeError: &#39;Person&#39; object has no attribute &#39;__name&#39;# 小技巧a._Person__name
登录后复制

实例方法( instance method )

实例方法,以self作为第一个参数,当它被调用时,Python会把调用该方法的的对象作为self参数传入。

class A():
    count = 2
    def __init__(self): # 这就是一个实例方法
        A.count += 1
登录后复制

类方法 @classmethod

class A():
    count = 2
    def __init__(self):
        A.count += 1    @classmethod
    def hello(h):
        print("hello",h.count)
登录后复制

注意,使用h.count(类特征),而不是self.count(对象特征)。

静态方法 @staticmethod

class A():    @staticmethod
    def hello():
        print("hello, staticmethod")
>>> A.hello()
登录后复制

创建即用,优雅不失风格。

特殊方法(sqecial method)

一个普通方法:

class word():
    def __init__(self, text):
        self.text = text
    def equals(self, word2): #注意
        return self.text.lower() == word2.text.lower()
a1 = word(&#39;aa&#39;)
a2 = word(&#39;AA&#39;)
a3 = word(&#39;33&#39;)
a1.equals(a2)
# True
登录后复制

使用特殊方法:

class word():
    def __init__(self, text):
        self.text = text    def __eq__(self, word2): #注意,使用__eq__
        return self.text.lower() == word2.text.lower()
a1 = word(&#39;aa&#39;)
a2 = word(&#39;AA&#39;)
a3 = word(&#39;33&#39;)
a1 == a2# True
登录后复制

# True

其他还有:

*方法名*                        *使用*
__eq__(self, other)            self == other
__ne__(self, other)            self != other
__lt__(self, other)            self < other
__gt__(self, other)            self > other
__le__(self, other)            self <= other
__ge__(self, other)            self >= other

__add__(self, other)        self + other
__sub__(self, other)        self - other
__mul__(self, other)        self * other
__floordiv__(self, other)    self // other
__truediv__(self, other)        self / other
__mod__(self, other)        self % other
__pow__(self, other)        self ** other

__str__(self)                str(self)
__repr__(self)                repr(self)
__len__(self)                len(self)
登录后复制

文本字符串

&#39;%-10d | %-10f | %10s | %10x&#39; % ( 1, 1.2, &#39;ccc&#39;, 0xf )
#
&#39;1          | 1.200000   |        ccc |         33&#39;
登录后复制

{} 和 .format

&#39;{} {} {}&#39;.format(11,22,33)
# 11 22 33
&#39;{2:2d} {0:-10d} {1:10d}&#39;.format(11,22,33)
# :后面是格式标识符
# 33 11 22

&#39;{a} {b} {c}&#39;.format(a=11,b=22,c=33)
登录后复制


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

PHP和Python:比较两种流行的编程语言 PHP和Python:比较两种流行的编程语言 Apr 14, 2025 am 12:13 AM

PHP和Python各有优势,选择依据项目需求。1.PHP适合web开发,尤其快速开发和维护网站。2.Python适用于数据科学、机器学习和人工智能,语法简洁,适合初学者。

debian readdir如何与其他工具集成 debian readdir如何与其他工具集成 Apr 13, 2025 am 09:42 AM

Debian系统中的readdir函数是用于读取目录内容的系统调用,常用于C语言编程。本文将介绍如何将readdir与其他工具集成,以增强其功能。方法一:C语言程序与管道结合首先,编写一个C程序调用readdir函数并输出结果:#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

Python和时间:充分利用您的学习时间 Python和时间:充分利用您的学习时间 Apr 14, 2025 am 12:02 AM

要在有限的时间内最大化学习Python的效率,可以使用Python的datetime、time和schedule模块。1.datetime模块用于记录和规划学习时间。2.time模块帮助设置学习和休息时间。3.schedule模块自动化安排每周学习任务。

Debian OpenSSL如何配置HTTPS服务器 Debian OpenSSL如何配置HTTPS服务器 Apr 13, 2025 am 11:03 AM

在Debian系统上配置HTTPS服务器涉及几个步骤,包括安装必要的软件、生成SSL证书、配置Web服务器(如Apache或Nginx)以使用SSL证书。以下是一个基本的指南,假设你使用的是ApacheWeb服务器。1.安装必要的软件首先,确保你的系统是最新的,并安装Apache和OpenSSL:sudoaptupdatesudoaptupgradesudoaptinsta

Debian上GitLab的插件开发指南 Debian上GitLab的插件开发指南 Apr 13, 2025 am 08:24 AM

在Debian上开发GitLab插件需要一些特定的步骤和知识。以下是一个基本的指南,帮助你开始这个过程。安装GitLab首先,你需要在Debian系统上安装GitLab。可以参考GitLab的官方安装手册。获取API访问令牌在进行API集成之前,首先需要获取GitLab的API访问令牌。打开GitLab仪表盘,在用户设置中找到“AccessTokens”选项,生成一个新的访问令牌。将生成的

apache属于什么服务 apache属于什么服务 Apr 13, 2025 pm 12:06 PM

Apache是互联网幕后的英雄,不仅是Web服务器,更是一个支持巨大流量、提供动态内容的强大平台。它通过模块化设计提供极高的灵活性,可根据需要扩展各种功能。然而,模块化也带来配置和性能方面的挑战,需要谨慎管理。Apache适合需要高度可定制、满足复杂需求的服务器场景。

apache是什么语言写的? apache是什么语言写的? Apr 13, 2025 pm 12:42 PM

Apache是用C语言编写的。该语言提供了速度、稳定性、可移植性和直接硬件访问,使其成为网络服务器开发的理想选择。

PHP和Python:代码示例和比较 PHP和Python:代码示例和比较 Apr 15, 2025 am 12:07 AM

PHP和Python各有优劣,选择取决于项目需求和个人偏好。1.PHP适合快速开发和维护大型Web应用。2.Python在数据科学和机器学习领域占据主导地位。

See all articles