So Python has many "magic" methods, marked by double underscores surrounding the name. (for this reason, they're also sometimes called "dunder" methods.) Rake Ketter's guide on the subject is the best you'll find, it's very clear. We're just going to address __init__
here.
So __init__
is basically a method that gets called when you create a new "instance" of a class. Let's examine this with dogs...
# So first we're going to create a new "Dog" object. A dog knows it's name and how to bark.
class Dog(object):
def __init__(self, name, woof): # __init__ takes a couple variables, and `self`...
self.name = name # and assigns them as properties of "self".
self.woof = woof
def speak(self):
return "%(name)s says: %(woof)s %(woof)s %(woof)s" % {
"name": self.name, # here we access the value we set earlier for "name"
"woof": self.woof # same for "woof".
}
def muzzle(self):
self.woof = "mmf" # we can also set properties on self in methods.
# Now that we've defined `Dog`, we can create a couple.
fido = Dog("Fido", "arf") # little dog, little bark
hercules = Dog("Hercules", "WOOF") # big dog, big bark
# Even though these are the same class (`Dog`) they're separate instances. So we can do the following:
assert fido.speak() == "Fido says: arf arf arf"
assert herules.speak() == "Hercules says: WOOF WOOF WOOF"
# Dogs can be muzzled, and it makes them quieter. So let's muzzle Hercules, he's very loud:
hercules.muzzle()
assert hercules.speak() == "Hercules says: mmf mmf mmf"