python带星号函数

默认值函数参数。这种函数定义时,第一个有默认值的参数后的每一个参数都必须提供默认值。传参时,可以直接传参,也可以以“默认值参数名=value”的形式传参。

单星号函数参数。单星号函数参数接收的参数组成一个元组。

单星号参数,把接收的参数作为元组,如果直接传元组类型的值,则传递的元组值作为了星号参数的元组中的一个元素。若要把元组值就作为星号参数的参数值,在元组值前加上“*”即可,不过此时,就不能在加了“*”的元组后,追加任何值了。

双星号函数参数。双星号函数参数接收的参数组成一个字典。必须采用默认值传参的“args = value”的方式。同时,“=”前的字段成了字典的键,“=”后的字段成了字典的值。即,双星号参数接收的参数作为字典。若想把字典值就作为星号参数的参数值,那么该怎么办呢?同单星号参数,在字典值前加上“**”,同时其后不能添加任何值。


#!/usr/bin/python

def singalStar(common, *rest):

    print("Common args: ", common)

    print("Rest args: ", rest)


def doubleStar(common, **double):

    print("Common args: ", common)

    print("Double args: ", double)


def singalAndDoubleStar(common, *single, **double):

    print("Common args: ", common)

    print("Single args: ", single)

    print("Double args: ", double)

def defaultValueArgs(common, defaultStr = "default", defaultNum = 0):

    print("Common args", common)

    print("Default String", defaultStr)

    print("Default Number", defaultNum) 

if __name__ == "__main__":

    defaultValueArgs("Test")

    defaultValueArgs("Test", "defaultqqq", defaultNum = 1)


    singalStar("hello")

    singalStar("hello", "world", 000)

    singalStar("hello", ("world", 000))

    singalStar("hello", ("world", 000), {123: 123})

    singalStar("hello", *("world", 000))

#    singalStar("hello", *("world", 000), "123")    #error


    doubleStar("hello")

    doubleStar("hello", x = "Test", y = 24)

    doubleStar("hello", **{"name": "Test", "age": 24})

#    doubleStar("hello", {"name": "Test", "age": 24})    #error

    singalAndDoubleStar("hello")

    singalAndDoubleStar("hello", "world", 000)

    singalAndDoubleStar("hello", "world", 000, {"name": "Test", "age": 24})

    singalAndDoubleStar("hello", "world", 000, **{"name": "Test", "age": 24})

    singalAndDoubleStar("hello", ("world", 000), {"name": "Test", "age": 24})

#    singalAndDoubleStar("hello", *("world", 000), {"name": "Test", "age": 24})      #error

    singalAndDoubleStar("hello", *("world", 000), **{"name": "Test", "age": 24})

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,569评论 19 139
  • Scala与Java的关系 Scala与Java的关系是非常紧密的!! 因为Scala是基于Java虚拟机,也就是...
    灯火gg阅读 3,608评论 1 24
  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,369评论 4 16
  • //Clojure入门教程: Clojure – Functional Programming for the J...
    葡萄喃喃呓语阅读 4,050评论 0 7
  • 有子曰:其为人也孝弟,而好犯上者,鲜矣;不好犯上,而好作乱者,未之有也。君子务本,本立而道生。孝弟也者,其为人本与...
    紫祺阅读 188评论 0 0

友情链接更多精彩内容