zoukankan      html  css  js  c++  java
  • Python类中的self的作用

    Python编写类的时候,每个函数第一个参数都是self。后来对Python越来越熟悉,再回头看self的概念,慢慢就明白了。

    谷歌上有一段解释很到位,贴出来给大家:

    self represents the instance of the class. By using the "self" keywork we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is parameter in function and user can use another parameter name in place of it.

    意思就是:self 代表了类的实例。 通过使用关键字"self", 我们可以获取类的特性和方法。它将属性与给定参数绑定。self名称不是必须的,在python中self不是关键词,你可以定义成a或b或其他名字都可以,但是约定俗成,不要搞另类,大家会不明白的。

    首先明确的是self只有在类的方法中才会有,独立的函数或方法不必带有self的。self在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。

    self指的是类实例对象本身(注意:不是类本身)。 以下是一个列子

    总结:

    self在定义类时需要定义, 但是在调用时会自动传入。

    self的名字并不是规定死的,但最好还是按照约定用self

    self总是指调用是的类实例对象 

  • 相关阅读:
    命令返回值
    PowerShell脚本传递参数
    HTTP 错误 404.3
    xcopy拷贝判断是否成功 robocopy排除子目录
    WinRAR压缩
    批处理命令随笔
    Android Studio3.0中dependencies依赖由compile变为implementation的区别
    compileSdkVersion, minSdkVersion 和 targetSdkVersion详解
    Android Studio工程Gradle编译报错
    rsync应用实例
  • 原文地址:https://www.cnblogs.com/elitphil/p/11880758.html
Copyright © 2011-2022 走看看