python-类的学习,面向对象编程

在python的类中,我们可以看到有的成员函数的参数中有self和other

那么他们到底是什么呢?

下面看一个程序:

class Student:
    def __init__(self):#构造函数
        self.name = 'liu'
        self.age = 23
    def compAge(self,other):
        if self.age < other.age:
            print('咱比人家小')
        else:
            print('不比人家小')
            
stu1 = Student()
print(stu1.age)

stu2 = Student()
stu2.age = 25
print(stu2.age)

stu1.compAge(stu2)

成员函数compAge(self,other)用于比较两个对象(对象即类的实例化)的成员变量的大小,其中参数有两个self,other。

在调用这个成员函数的时候不是compAge(stu1,stu2),而是直接采用stu1.compAge(stu2),那么other可以认为是函数的另一个形参,函数的第一个形参即对象本身-stu1

你可能感兴趣的:(数据结构与算法分析)