def 函数名 ( 参数 ) :
函数体
- # 自定义函数
- def func(a, b):
- return a + b
-
- # 调用函数
- func(1, 2)
- def func1(num):
- num * 10
-
- num1 = 10
- func1(num1)
- print(num1) # 10
-
-
- def func2(lst):
- lst[0] *= 10
-
- lst1 = [10]
- func2(lst1)
- print(lst1[0]) # 100
设置默认参数时,必选参数在前
,默认参数在后
- def func3(num1, num2=10):
- print(num1 + num2)
-
- func3(1, 2) # 3
- func3(1) # 11
可变参数/不定长参数,可以输入任意个参数,在函数内作为元组Tuple使用
- def func4(*nums):
- sum = 0
- for num in nums:
- sum += num
- return sum
-
- print(func4(1, 2, 3)) # 6
- print(func4(1, 2, 3, 4)) # 10
指定参数名传参,不一定按固定顺序
- def func5(name, age):
- print(name, age)
-
- func5(age=18, name="XiaoMing")
函数都有返回值,默认返回None
Lambda表达式
- func6 = lambda a, b: a + b
-
- print(func6(1, 2)) # 3
class 类名(基类):
默认自动继承object类。
- class TestClass:
- name = "Test Class"
-
- # 实例化
- test = TestClass()
- print(test.name)
- class TestClass:
- publicname = "PublicName"
- __privatename = "PrivateName"
-
- def testfunc1(self):
- print(self.publicname)
-
- def testfunc2(self):
- print(self.__privatename)
-
- def __testfunc3(self):
- print(self.publicname)
-
- def __testfunc4(self):
- print(self.__privatename)
-
- def testfunc55(self):
- print(self.publicname)
-
- testfunc5 = classmethod(testfunc55)
-
- @classmethod
- def testfunc6(cls):
- print(cls.publicname)
-
- def testfunc77():
- print("static func")
-
- testfunc7 = staticmethod(testfunc77)
-
- @staticmethod
- def testfunc8():
- print("static func")
-
- testfunc7()
- testfunc8()
-
-
- # 实例调用
- testclass = TestClass()
- print(testclass.publicname)
- testclass.testfunc1()
- testclass.testfunc2()
- testclass.testfunc5()
- testclass.testfunc6()
- testclass.testfunc7()
- testclass.testfunc8()
-
- # 类名调用
- TestClass.testfunc5()
- TestClass.testfunc6()
- TestClass.testfunc7()
- TestClass.testfunc8()