1、概述
1.1 場景
我們在使用 Python 中的 方法 method 時,經常會看到 參數中帶有 self,但是我們也沒對這個參數進行指派,那麼這個參數到底是啥意思呢?
2、知識點
2.1 成員函數(m) 和 普通方法(f)
Python 中的 "類方法" 必須有一個額外的 第一個參數名稱(名稱任意,不過推薦 self),而 "普通方法"則不需要。
m、f、c 都是代碼自動提示時的 左邊字母(method、function、class)
# -*- 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)
2.2 類函數,靜态函數
類函數一般用參數 cls
靜态函數無法使用 self 或 cls
class Test(object):
def __init__(self):
print('我是構造函數。。。。')
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("成員函數")
Test.class_foo("類函數")
Test.static_foo("靜态函數")
show("普通方法")
輸出結果:
我是構造函數。。。。
成員函數
類函數
靜态函數
普通方法
時間: 2019-08-27