Python类中self参数用法详解
作者:猪笨是念来过倒 时间:2023-06-19 00:40:54
Python编写类的时候,每个函数参数第一个参数都是self,一开始我不管它到底是干嘛的,只知道必须要写上。后来对Python渐渐熟悉了一点,再回头看self的概念,似乎有点弄明白了。
首先明确的是self只有在类的方法中才会有,独立的函数或方法是不必带有self的。self在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。
self名称不是必须的,在python中self不是关键词,你可以定义成a或b或其它名字都可以,但是约定成俗(为了和其他编程语言统一,减少理解难度),不要搞另类,大家会不明白的。
下例中将self改为myname一样没有错误:
class Person:
def __init__(myname,name):
myname.name=name
def sayhello(myname):
print ('My name is:',myname.name)
p=Person('aoteman')
print(p)
self指的是类实例对象本身(注意:不是类本身)。
class Person:
def __init__(self,name):
self.name=name
def sayhello(self):
print ('My name is:',self.name)
p=Person('aoteman')
print(p)
在上述例子中,self指向Person的实例p。 为什么不是指向类本身呢,如下例子:
class Person:
def __init__(self,name):
self.name=name
def sayhello(self):
print ('My name is:',self.name)
p1 = Person('aoteman')
p2 = Person('xiaoyiyi')
print(p1)
如果self指向类本身,那么当有多个实例对象时,self指向哪一个呢?
总结
self在定义时需要定义,但是在调用时会自动传入。
self的名字并不是规定死的,但是最好还是按照约定是用self
来源:https://blog.csdn.net/liao392781/article/details/82703586
标签:Python,self
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
jupyter notebook实现显示行号
2022-11-20 03:51:40
![](https://img.aspxhome.com/file/2023/6/103616_0s.jpg)
Python decorator拦截器代码实例解析
2022-04-07 11:03:47
MySQL约束与索引概念详解
2024-01-28 17:06:39
![](https://img.aspxhome.com/file/2023/1/108881_0s.png)
对SQL Server聚集索引的指示综合描述
2010-08-31 14:25:00
MySQL详细讲解多表关联查询
2024-01-13 23:47:15
![](https://img.aspxhome.com/file/2023/4/68584_0s.png)
如何将txt文本中的数据轻松导入MySQL表中
2009-03-06 17:35:00
CSS制作11种风格不同的特效文字
2010-10-20 20:08:00
在ASP.NET页面中如何利用JAVASCRIPT脚本向IFRAMES和POPUP传值
2007-09-23 13:18:00
使用 Django Highcharts 实现数据可视化过程解析
2022-12-27 19:18:51
![](https://img.aspxhome.com/file/2023/8/99238_0s.png)
asp获取文件md5值
2008-10-13 09:10:00
Python基于TCP实现会聊天的小机器人功能示例
2022-11-08 13:03:33
![](https://img.aspxhome.com/file/2023/8/82748_0s.png)
python中h5py开源库的使用样例详解
2022-03-30 00:37:03
SQL Server 自动化管理分区设计方案(图解)
2011-07-21 17:25:04
Python+OpenCV实现基于颜色的目标识别
2022-10-28 02:57:27
![](https://img.aspxhome.com/file/2023/2/93592_0s.jpg)
Vue2 模板template的四种写法总结
2023-07-02 16:50:18
Python matplotlib的spines模块实例详解
2021-10-11 06:37:58
![](https://img.aspxhome.com/file/2023/9/110189_0s.jpg)
编写安全的SQL Server扩展存储过程
2008-11-25 11:16:00
Python利用pynimate实现制作动态排序图
2023-05-25 03:31:32
![](https://img.aspxhome.com/file/2023/4/88994_0s.gif)
Python数据分析之pandas函数详解
2021-09-04 21:54:52
Python and、or以及and-or语法总结
2021-11-08 01:52:36