python compare函数_Python函数宝典:大神精辟总结“传参语法糖”

本文详细介绍了Python编程中的几种语法糖,包括函数、方法的区别,参数默认值,可变参数,键值对参数,Keyword-Only和Positional-Only参数,以及函数的引用修改。同时提到了Python的first-class function特性,以及类型标注的作用。文章最后分享了Python之禅,强调代码的简洁性和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Python中将面向过程方式声明的函数(即不归属于类)称为函数(function),而面向对象方式声明的函数称为方法(method)。

语法糖1:

# 函数

def greeting():

print("function")

class Human:

# 实例方法

def greeting(self):

print("instance method")

# 类方法

@classmethod

def write(cls):

print("class method")

# 静态方法

@staticmethod

def read():

print("static method")

语法糖2:

参数可以具备默认值,对比Objective-C由于这项特性的缺失需要实现构造方法和便利构造方法。

def greeting(name = "Jack Ma"):

print("Hello", name)

>>> greeting()

Hello Jack Ma

>>> greeting("Pony Ma")

Hello Pony Ma

语法糖3:通过*args表示可变参数。

def calc(name, *args):

spent = 0

for v in args:

spent += v

print(name, "spent money:", spent)

>>> calc("Jack Ma", 1000000, 2000000)

Jack Ma spent money: 3000000

传入的参数通过type(args)可以检查类型为元组(tuple),除了函数声明外函数调用亦然。

>>> args = (1000000, 2000000, 3000000) # [1, 2, 3]同理

>>> calc("Jack Ma", *args)

Jack Ma spent money: 6000000

通过**kwargs以键值对的形式表示可变参数。

def calc(name, **kwargs):

spent = name + " spent on:"

for k, v in kwargs.items():

spent += "%s=%s," % (k, v)

print(spent)

>>> calc("Jack Ma", eating=10000, shopping=20000)

Jack Ma spent on:eating=10000,shopping=20000

同理,函数调用亦然。

>>> kwargs = {"eating":10000, "shopping":20000}

>>> calc("Jack Ma", **kwargs)

Jack Ma spent on:eating=10000,shopping=20000

自Python1起就支持通过位置和参数名称两种方式传递参数,如对于原型为def add(x, y)的函数,同时支持以下两种调用方式。

add(1, 2)

add(x=1, y=2)

语法糖4:

Keyword-Only Arguments (PEP-3012)

函数声明时,参数列表中单独的*表示在此之后的参数仅支持通过名称进行传递。通过这个语法可以在可变参数列表之后传递其他参数。

def compare(a, b, *, key=None):

pass

>>> compare(1, 2, 3) # 调用失败

Traceback (most recent call last):

File "", line 1, in

TypeError: compare() takes 2 positional arguments but 3 were given

>>> compare(1, 2, key=3) # 调用成功

语法糖5:

Positional-Only Parameters (PEP-570)

函数声明时,参数列表中单独的/表示在此之前的参数仅支持通过位置进行传递。这个语法主要解决部分函数的参数没有实际意义,后续可能会进行修改,避免通过名称传递参数在名称修改后失效。比如int(x="1")中x并没有实际意义,而且相比int("1")可读性有所不足。

def name(positional_only_parameters, /, positional_or_keyword_parameters,

*, keyword_only_parameters):

pass

此外,官方文档表述这个语法还解决了某个边界条件下的调用失败。对于以下函数:

def foo(name, **kwargs):

return 'name' in kwargs

当我们传递的kwargs拥有一个"name"的key时会调用失败,如下。

>>> foo(1, **{'name': 2})

Traceback (most recent call last):

File "", line 1, in

TypeError: foo() got multiple values for argument 'name'

通过以下方式可以解决这个问题。

def foo(name, /, **kwargs):

return 'name' in kwargs

语法糖6:

如何修改参数的引用,最简单的方式是将入参按顺序以元组进行返回。

语法糖7:

由于Python的first-class function特性,函数作为一等公民可以像其他类型一样进行传递和赋值。比如max函数原型可以传入一个用于比较的函数,当然函数也可以被重新赋值。

>>> max=min

>>> max(19,9)

9

全局函数和关键字有时候会不易分辨,比如print在Python2中是关键字,而在Python3中是内置函数。可以通过下列方式获取关键字列表。

>>> import keyword

>>> keyword.kwlist

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

语法糖8:

类型标注(Type Hint)通过:type表示参数类型,由于Python动态类型的特性Python 运行时并不强制标注函数和变量类型,类型标注可被用于IDE等第三方工具。如下:

def greeting(name: str) -> str:

return 'Hello ' + name

Python作为这个榜单的常青树且仍然保持着上升趋势,身边也有不少人自学这门语言。文章的最后摘录Python之禅与各位共勉。

>>> python3

>>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren't special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch.

Now is better than never.

Although never is often better than *right* now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值