详解Python self 参数

yipeiwu_com6年前Python基础

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

输出结果:

我是构造函数。。。。
成员函数
类函数
静态函数
普通方法

总结

以上所述是小编给大家介绍的Python self 参数,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python字典,函数,全局变量代码解析

字典 dict1 = {'name':'han','age':18,'class':'first'} print(dict1.keys()) #打印所有的key值 print(...

浅析Python 3 字符串中的 STR 和 Bytes 有什么区别

浅析Python 3 字符串中的 STR 和 Bytes 有什么区别

Python2的字符串有两种:str和Unicode,Python3的字符串也有两种:str和Bytes。Python2的str相当于Python3的Bytes,而Unicode相当于P...

python DataFrame获取行数、列数、索引及第几行第几列的值方法

1、df=DataFrame([{‘A':'11','B':'12'},{‘A':'111','B':'121'},{‘A':'1111','B':'1211'}]) print d...

pandas的qcut()方法详解

pandas的qcut()方法详解

pandas的qcut可以把一组数字按大小区间进行分区,比如 data = pd.Series([0,8,1,5,3,7,2,6,10,4,9]) 比如我要把这组数据分成两部分,一...

举例讲解Django中数据模型访问外键值的方法

先设置一个关于书本(book)的数据模型: from django.db import models class Publisher(models.Model): name...