Python 原创基础教程
第七章 类方法中的特殊参数
类参数self&cls
- staticmethod(静态方法):可以没有self,当普通函数使用
- classmethod(类方法):第一个参数是cls,代表类本身
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class A(object): def foo1(self): print("Hello",self) @staticmethod def foo2(): print("hello") @classmethod def foo3(cls): print("hello",cls) >>> a = A() >>> a.foo1() Hello <__main__.A object at 0x9f6abec> >>> A.foo1(a) Hello <__main__.A object at 0x9f6abec> >>> A.foo2() hello >>> A.foo3() hello <class '__main__.A'> >>> A <class '__main__.A'>
|
函数参数(*args & **kwargs)
*args 其中args只是个名字,可以是其他字母
实例1
1 2 3 4 5 6
| def test_args(normal_arg, *args): print("first normal arg:" + normal_arg) for arg in args: print("another arg through *args :" + arg)
test_args("normal", "python", "java", "C#")
|
**kwargs意思相同,但参数形式是字典形式
实例2
1 2 3 4 5 6 7 8 9 10
| def fun_kwargs(farg, **kwargs): print "arg:", farg for key in kwargs: print "another key and arg: %s: %s" % (key, kwargs[key]) fun_kwargs(farg=1, myarg2="two", myarg3=3) dic = {"args2":"two", "args3":3} fun_kwargs(fargs=1, **dic) #调用方式1
|
实例3
1 2 3 4 5 6 7 8
| def fun_kwargs1(arg1, arg2, arg3): print "arg1:", arg1 print "arg2:", arg2 print "arg3:", arg3 kwargs = {"arg2":"two", "arg3":3} fun_kwargs1(1, **kwargs)
|