亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解Python self 參數

 更新時間:2019年08月30日 15:55:33   作者:魚丸丶粗面  
這篇文章主要介紹了Python self 參數詳解,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下

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 類函數,靜態(tài)函數

類函數一般用參數 cls

靜態(tài)函數無法使用 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("靜態(tài)函數")
 show("普通方法")

輸出結果:

我是構造函數。。。。
成員函數
類函數
靜態(tài)函數
普通方法

總結

以上所述是小編給大家介紹的Python self 參數,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!

相關文章

最新評論