1. 在python对象模型中,当通过实例对象调用方法时,默认会把档期那实例对象当作第一个参数传递给方法。所以如果需要使用实例对象调用类中的方法,在类中定义方法时,通常第一个参数的名称为self。但是self只是惯例,可以用其他名字代替。
>>> class test:
def add(a,b):return a+b
def add2(self,a,b):return a+b
>>> test.add(2,3)
5
>>> test.add2(2,3) #使用test调用方法,add2有三个参数
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
test.add2(2,3)
TypeError: add2() missing 1 required positional argument: 'b'
>>> test.add2(2,3,4)
7
>>> x=test()
>>> x.add(2,3) #使用实例对象调用方法,默认会把实例对象自己的引用(self)当作第一个参数传给add(),
Traceback (most recent call last):
File "<pyshell#73>", line 1, in <module>
x.add(2,3)
TypeError: add() takes 2 positional arguments but 3 were given
>>> x.add2(2,3)
5
>>>