欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Python self 參數(shù)

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

1、概述

1.1 場景

我們在使用 Python 中的 方法 method 時,經(jīng)常會看到 參數(shù)中帶有 self,但是我們也沒對這個參數(shù)進(jìn)行賦值,那么這個參數(shù)到底是啥意思呢?

2、知識點(diǎn)

2.1 成員函數(shù)(m) 和 普通方法(f)

Python 中的 "類方法" 必須有一個額外的 第一個參數(shù)名稱(名稱任意,不過推薦 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 類函數(shù),靜態(tài)函數(shù)

類函數(shù)一般用參數(shù) cls

靜態(tài)函數(shù)無法使用 self 或 cls

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("普通方法")

輸出結(jié)果:

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

總結(jié)

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

相關(guān)文章

最新評論