博客
关于我
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/

你可能感兴趣的文章
NOPI读取Excel
查看>>
NoSQL&MongoDB
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>
npm start运行了什么
查看>>
npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
查看>>
NPM使用前设置和升级
查看>>
npm入门,这篇就够了
查看>>
npm切换到淘宝源
查看>>
npm前端包管理工具简介---npm工作笔记001
查看>>
npm和yarn清理缓存命令
查看>>
npm和yarn的使用对比
查看>>
npm学习(十一)之package-lock.json
查看>>