0

0

Python 函数 类 语法糖

高洛峰

高洛峰

发布时间:2016-11-22 15:56:07

|

1576人浏览过

|

来源于php中文网

原创

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 = ['one','two','three']
list(zip(a,b))
# [(1, 'one'), (2, 'two'), (3, 'three')]

列表推导式

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 = 'Hello World'
s = { k : strs.count(k) for k in set(strs) }

集合推导式

{expression for expression in iterable }

元组没有推导式

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

生成器推导式

>>> num = ( x for x in range(5) )>>> num
...: at 0x7f50926758e0>

函数

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

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

do(a=1,b=3,c=2)

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

立即学习Python免费学习笔记(深入)”;

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,'d')

**kwargs 收集关键字参数

def do(**kwargs):
  print(kwargs)
do(a=1,b=2,c='la')
# {'c': 'la', 'a': 1, 'b': 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()
... 

装饰器

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

# 一个装饰器
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():
    '''This is the amazing.
    Hello
    world'''
    print("The function named: ", amazing.__name__)
    print("The function docstring is: \n", amazing.__doc__)

异常处理,try...except

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

网奇Eshop网络商城系统
网奇Eshop网络商城系统

网奇.NET网络商城系统是基于.Net平台开发的免费商城系统。功能强大,操作方便,设置简便。无需任何设置,上传到支持asp.net的主机空间即可使用。系统特色功能:1、同时支持Access和SqlServer数据库;2、支持多语言、多模板3、可定制缺货处理功能4、支持附件销售功能5、支持会员组批发功能6、提供页面设计API函数7、支持预付款功能8、配送价格分地区按数学公式计算9、商品支持多类别,可

下载
>>> l = [1,2,3]
>>> index = 5
>>> l[index]
Traceback (most recent call last):
  File "", line 1, in 
  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 == 'q':        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 = ['a','b','c','AA']
for i in words:
    if i.isupper():
        raise UppercaseException(i)
# error
Traceback (most recent call last):
  File "", line 3, in 
__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('me', 'me@me.me')>>> a.name... 'me'>>> a.email... 'me@me.me'

self.__name 保护私有特性

class Person():
    def __init__(self, name):
        self.__name = name
a = Person('me')>>> a.name... AttributeError: 'Person' object has no attribute '__name'# 小技巧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('aa')
a2 = word('AA')
a3 = word('33')
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('aa')
a2 = word('AA')
a3 = word('33')
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)

文本字符串

'%-10d | %-10f | %10s | %10x' % ( 1, 1.2, 'ccc', 0xf )
#
'1          | 1.200000   |        ccc |         33'

{} 和 .format

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

'{a} {b} {c}'.format(a=11,b=22,c=33)

相关文章

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

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

相关专题

更多
excel制作动态图表教程
excel制作动态图表教程

本专题整合了excel制作动态图表相关教程,阅读专题下面的文章了解更多详细教程。

20

2025.12.29

freeok看剧入口合集
freeok看剧入口合集

本专题整合了freeok看剧入口网址,阅读下面的文章了解更多网址。

65

2025.12.29

俄罗斯搜索引擎Yandex最新官方入口网址
俄罗斯搜索引擎Yandex最新官方入口网址

Yandex官方入口网址是https://yandex.com;用户可通过网页端直连或移动端浏览器直接访问,无需登录即可使用搜索、图片、新闻、地图等全部基础功能,并支持多语种检索与静态资源精准筛选。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

197

2025.12.29

python中def的用法大全
python中def的用法大全

def关键字用于在Python中定义函数。其基本语法包括函数名、参数列表、文档字符串和返回值。使用def可以定义无参数、单参数、多参数、默认参数和可变参数的函数。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

16

2025.12.29

python改成中文版教程大全
python改成中文版教程大全

Python界面可通过以下方法改为中文版:修改系统语言环境:更改系统语言为“中文(简体)”。使用 IDE 修改:在 PyCharm 等 IDE 中更改语言设置为“中文”。使用 IDLE 修改:在 IDLE 中修改语言为“Chinese”。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

16

2025.12.29

C++的Top K问题怎么解决
C++的Top K问题怎么解决

TopK问题可通过优先队列、partial_sort和nth_element解决:优先队列维护大小为K的堆,适合流式数据;partial_sort对前K个元素排序,适用于需有序结果且K较小的场景;nth_element基于快速选择,平均时间复杂度O(n),效率最高但不保证前K内部有序。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

12

2025.12.29

php8.4实现接口限流的教程
php8.4实现接口限流的教程

PHP8.4本身不内置限流功能,需借助Redis(令牌桶)或Swoole(漏桶)实现;文件锁因I/O瓶颈、无跨机共享、秒级精度等缺陷不适用高并发场景。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

134

2025.12.29

抖音网页版入口在哪(最新版)
抖音网页版入口在哪(最新版)

抖音网页版可通过官网https://www.douyin.com进入,打开浏览器输入网址后,可选择扫码或账号登录,登录后同步移动端数据,未登录仅可浏览部分推荐内容。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

63

2025.12.29

快手直播回放在哪看教程
快手直播回放在哪看教程

快手直播回放需主播开启功能才可观看,主要通过三种路径查看:一是从“我”主页进入“关注”标签再进主播主页的“直播”分类;二是通过“历史记录”中的“直播”标签页找回;三是进入“个人信息查阅与下载”里的“直播回放”选项。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

18

2025.12.29

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Django 教程
Django 教程

共28课时 | 2.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 0.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号