打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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)
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

  • 20

  • 21

  • 22

  • 23

2.2 类函数,静态函数

  • 类函数一般用参数 cls

  • 静态函数无法使用 selfcls

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('普通方法')
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

  • 20

  • 21

  • 22

  • 23

  • 24

  • 25

  • 26

  • 27

  • 28

  • 29

输出结果:

我是构造函数。。。。成员函数类函数静态函数普通方法
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python实战教程:修饰器精讲!(2019下半年篇)
Python基础语法大全及知识点总结(珍藏版)
Python中的函数和方法
五、Python self用法详解
【Python】技巧
Python线程:同时运行2个不同的函数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服