博客
关于我
python3面向对象--python3中类方法的特殊性与self
阅读量:611 次
发布时间:2019-03-12

本文共 547 字,大约阅读时间需要 1 分钟。

类方法的特殊性

在面向对象编程的语言中,类方法的定义通常遵循特定的规则。而在Python中,这些规则与其他语言有所不同,值得特别关注。

类方法的定义在Python中必须包含参数self,并且它是参数列表中的第一个参数。self表示类实例,与Java中的this概念相似。尽管self不是限定关键字,但在Python中习惯上统一使用self作为参数名。

例如,在类Persion中:

class Persion:    def sayHello(self):        print("hello world!")    persison2 = Persion()    persion2.sayHello()  # 正确调用方式

如果方法定义不包含self参数,即使在调用时传递参数,也会导致错误:

def sayHello():    print("hello world!")persion2 = Persion()persion2.sayHello()  # 会抛出TypeError:sayHello() takes 0 positional arguments but 1 was given

因此,在定义类方法时,必须将self作为第一个参数,正确地将实例作为方法的第一参数传递。

转载地址:http://hbtxz.baihongyu.com/

你可能感兴趣的文章
npm发布自己的组件UI包(详细步骤,图文并茂)
查看>>
npm和yarn清理缓存命令
查看>>
npm和yarn的使用对比
查看>>
npm如何清空缓存并重新打包?
查看>>
npm学习(十一)之package-lock.json
查看>>
npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
查看>>
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>