设为首页 加入收藏

TOP

理解*arg 、**kwargs
2018-10-19 16:45:47 】 浏览:20
Tags:理解 arg kwargs

这两个是python中的可变参数。*args表示任何多个无名参数,它是一个tuple(元祖);**kwargs表示关键字参数,它是一个dict(字典)。
并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前。看下面例子:

 # https://godjango.com/105-understanding-args-and-kwargs/(例子来源)
1
def print_args(d1, d2, d3): 2 print(d1, d2, d3) 3 4 data = ('foo', 'bar', 'baz') 5 print_args(*data) # 在data之前使用一个星号,表示让函数接受任意多的位置参数。 6 >>> foo bar baz 7 8 def print_args(*args): 9 for arg in args: 10 print(arg) 11 print_args(1, 2, 3) 12 >>> 1 13 >>> 2 14 >>> 3 15 16 def print_args(*args): 17 print(args) 18 print_args(1, 2, 3) 19 >>> (1, 2, 3) 20 21 def print_args(a, b, c, *args): 22 print(a, b, c, args) 23 print_args(1, 2, 3, 4, 5) 24 >>> 1 2 3 (4, 5) 25 26 27 def print_kwargs(**kwargs): # 在参数名之前使用2个星号来支持任意多的关键字参数 28 print(kwargs) 29 print_kwargs(foo='bar', hello='world') 30 >>> {'foo': 'bar', 'hello': 'world'} 31 32 def print_kwargs(latitude=None, longitude=None): 33 print(latitude, longitude) 34 35 data = {'latitude': 0.00, 'longitude': 1.00} 36 print_data(**data) 37 >>> 0.00 1.00 38 39 def print_kwargs(lat=None, long=None, **kwargs): 40 print(lat, long, kwargs) 41 print_kwargs(1, 2, data='other') 42 >>> 1 2 {'data': 'other'} 43

 

 


 

Python super()函数用法

super() 函数是用于调用父类(超类)的一个方法。好处是可以避免直接调用父类的名字

值得注意的是,在python3中直接使用 super().xxx 代替 super(Class, self).xxx (Python2格式)

 

 # http://www.runoob.com/python/python-func-super.html(例子来源)
1
class FooParent(object): 2 def __init__(self): 3 self.parent = 'I\'m the parent.' 4 print ('Parent') 5 6 def bar(self,message): 7 print ("%s from Parent" % message) 8 9 class FooChild(FooParent): 10 def __init__(self): 11 # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类B的对象 FooChild 转换为类 FooParent 的对象 12 super(FooChild,self).__init__() 13 print ('Child') 14 15 def bar(self,message): 16 super(FooChild, self).bar(message) 17 print ('Child bar fuction') 18 print (self.parent) 19 20 if __name__ == '__main__': 21 fooChild = FooChild() 22 fooChild.bar('HelloWorld')

 

输出为:

1 Parent
2 Child
3 HelloWorld from Parent
4 Child bar fuction
5 I'm the parent.

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python递归函数、匿名函数、过滤.. 下一篇课时25:字典:当索引不好用时

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目