实例方法
创建实例方法时,第一个参数总是self。
您可以随意命名,但含义始终相同,您应该使用self,因为这是命名约定。
self(通常)在调用实例方法时被隐藏传递;它代表调用方法的实例。
这是一个名为 Inst 的类的示例,它有一个名为 introduce() 的实例方法:
class Inst:
def __init__(self, name):
self.name = name
def introduce(self):
print("Hello, I am %s, and my name is " %(self, self.name))
现在要调用这个方法,我们首先需要创建我们类的一个实例。
一旦我们有了一个实例,我们就可以在它上面调用introduce(),实例会自动传递为self:
myinst = Inst("Test Instance")
otherinst = Inst("An other instance")
myinst.introduce()
# outputs: Hello, I am <Inst object at x>, and my name is Test Instance
otherinst.introduce()
# outputs: Hello, I am <Inst object at y>, and my name is An other instance
如您所见,我们没有传递参数self,它是通过句号运算符隐藏传递的;我们调用Inst类的实例方法introduce,参数为myinst或otherinst。
这意味着我们可以调用Inst.introduce(myinst) 并得到完全相同的结果。
类方法
类方法的思想与实例方法非常相似,唯一的区别是我们现在将类本身作为第一个参数传递,而不是将实例作为第一个参数隐藏传递。
class Cls:
@classmethod
def introduce(cls):
print("Hello, I am %s!" %cls)
由于我们只向方法传递一个类,因此不涉及实例。
这意味着我们根本不需要实例,我们调用类方法就好像它是一个静态函数:
Cls.introduce() # same as Cls.introduce(Cls)
# outputs: Hello, I am <class 'Cls'>
注意Cls 再次被隐藏传递,所以我们也可以说Cls.introduce(Inst) 并得到输出"Hello, I am <class 'Inst'>。
这在我们从 Cls 继承类时特别有用:
class SubCls(Cls):
pass
SubCls.introduce()
# outputs: Hello, I am <class 'SubCls'>