1、概述
1.1 場景
我們在使用 Python 中的 方法 method
時,經(jīng)常會看到 參數(shù)中帶有 self
,但是我們也沒對這個參數(shù)進(jìn)行賦值,那么這個參數(shù)到底是啥意思呢?
2、知識點
2.1 成員函數(shù)(m) 和 普通方法(f)
# -*- coding: utf-8 -*-class Test(object): def add(self, a, b): # 輸出 a + b print(a + b) def show(self): # 輸出 'Hello World' print('Hello World')def display(a, b): # 輸出 a * b print(a * b)if __name__ == '__main__': test = Test() test.add(1, 2) test.show() display(1, 2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2.2 類函數(shù),靜態(tài)函數(shù)
class Test(object): def __init__(self): print('我是構(gòu)造函數(shù)。。。。') def foo(self, str): print(str) @classmethod def class_foo(cls, str): print(str) @staticmethod def static_foo(str): print(str)def show(str): print(str)if __name__ == '__main__': test = Test() test.foo('成員函數(shù)') Test.class_foo('類函數(shù)') Test.static_foo('靜態(tài)函數(shù)') show('普通方法')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
輸出結(jié)果:
我是構(gòu)造函數(shù)。。。。成員函數(shù)類函數(shù)靜態(tài)函數(shù)普通方法