【python学习】 self的使用

 

self的使用,当创建了类的时候,要将self参数写入,在使用该函数的时候,需要先将其实例化才能使用

类方法需要使用self参数,而普通方法不需要self参数

 

 

1、self是指自己的意思,是指实例对象自己,也就是s1 = Student(‘张三’,80) 中的"s1"。

2、使用self的意义是把name ,score这些属性变成实例自己的属性,类不能调用。

 使用示例

class Student:
    def __init__(self,name,score): 
        self.name = name        
        self.score = score
​
    def say_score(self):           
        print("{0}的分数是{1}".format(self.name,self.score))

s1 = Student('张三',80)  
s1.say_score()

3、因为在Python的解释器内部,当我们调用是s1.say_score()时,实际上Python解释成Student.say_score(s1),也就是说把self替换成类的实例。
s1.say_score()=Student.say_score(s1)

参考自网址 https://blog.csdn.net/fcygcyfv/article/details/123895271

posted @ 2022-06-07 11:19  someonezero  阅读(211)  评论(0编辑  收藏  举报