实例方法
创建实例方法时,第一个参数总是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 , and my name is Test Instance
otherinst.introduce()
# outputs: Hello, I am , and my name is An other instance
如您所见,我们没有传递参数self,它是用period运算符隐藏地传递的;我们调用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
注意,Cls被隐藏地传递,所以我们也可以说Cls.introduce(Inst)并获得输出"Hello, I am 。
当我们从Cls继承类时,这尤其有用:class SubCls(Cls):
pass
SubCls.introduce()
# outputs: Hello, I am