search
HomeBackend DevelopmentPython TutorialPython function class syntactic sugar

Python syntactic sugar

, newline connection

s = ''
s += 'a' + \
     'b' + \
     'c'
n = 1 + 2 + \
3
# 6

while, else outside the for loop

If the while loop ends normally (no break exit), else will be executed.

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() parallel iteration

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;)]

list comprehension

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]

dictionary comprehension

{ key_exp : value_exp fro expression in iterable }

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

set comprehension

{expression for expression in iterable }

tuple There is no derivation

I thought the tuple derivation was a list derivation and changed it into parentheses, but later I discovered the generator derivation.

Generator derivation

>>> num = ( x for x in range(5) )>>> num
...:<generator object <genexpr> at 0x7f50926758e0>

function

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

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)


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.