详解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自动化测试之从命令行运行测试用例with verbosity

python自动化测试之从命令行运行测试用例with verbosity

本文实例讲述了python自动化测试之从命令行运行测试用例with verbosity,分享给大家供大家参考。具体如下: 实例文件recipe3.py如下: class RomanN...

python3结合openpyxl库实现excel操作的实例代码

一.相关说明: 1、openpyxl(可读写excel表)专门处理Excel2007及以上版本产生的xlsx文件;2007一下的版本为xls结尾的文件,需要使用 xlrd和xlwt库进行...

python3.3教程之模拟百度登陆代码分享

复制代码 代码如下:#-*-coding:utf-8-*-'''Created on 2014年1月10日 @author: hhdys'''import urllib.request,...

Python饼状图的绘制实例

Python饼状图的绘制实例

import numpy as np import matplotlib.pyplot as plt labels = 'A', 'B', 'C', 'D' fracs = [15,...

Python3实现发送QQ邮件功能(html)

本文为大家分享了Python3实现发送QQ邮件功能:html,供大家参考,具体内容如下 之前已经成功发送了qq邮件。下面贴出html格式的qq邮件 import smtplib f...