理解*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.

 

转载于:https://www.cnblogs.com/linyuhong/p/9486917.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值