当前位置: 移动技术网 > IT编程>脚本编程>Python > 详解Python self 参数

详解Python self 参数

2019年09月06日  | 移动技术网IT编程  | 我要评论

英语四级考试题,濮阳采购,任家熠

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 参数,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网