Instance methods
When creating an instance method, the first parameter is always self
.
You can name it anything you want, but the meaning will always be the same, and you should use self
since it's the naming convention.
self
is (usually) passed hiddenly when calling an instance method; it represents the instance calling the method.
Here's an example of a class called Inst
that has an instance method called 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))
Now to call this method, we first need to create an instance of our class.
Once we have an instance, we can call introduce()
on it, and the instance will automatically be passed as 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
As you see, we're not passing the parameter self
. It gets hiddenly passed with the period operator. We're calling Inst
class's instance method introduce
, with the parameter of myinst
or otherinst
.
This means that we can call Inst.introduce(myinst)
and get the exact same result.
Class methods
The idea of a class method is very similar to an instance method, only difference being that instead of passing the instance hiddenly as a first parameter, we're now passing the class itself as a first parameter.
class Cls:
@classmethod
def introduce(cls):
print("Hello, I am %s!" %cls)
Since we're passing only a class to the method, no instance is involved.
This means that we don't need an instance at all, and we call the class method as if it was a static function:
Cls.introduce() # same as Cls.introduce(Cls)
# outputs: Hello, I am <class 'Cls'>
Notice that again Cls
is passed hiddenly, so we could also say Cls.introduce(Inst)
and get output "Hello, I am <class 'Inst'>
.
This is particularly useful when we're inheriting a class from Cls
:
class SubCls(Cls):
pass
SubCls.introduce()
# outputs: Hello, I am <class 'SubCls'>