Objects in Python

Python is based on object-oriented programming, or OOP. Even built-in variables like strings and integers are objects. They are objects of type string and of type integer, respectively. A particular variable, for example when x = 12, is considered an object instance. In this case, the variable x is an instance of type integer.

The 'type' is called a class. In that example, x is an instance of the integer class. A class is a template; a blueprint; the cookie cutter mold. The instance is the actual object, in this case 'x'.

Python comes with built-in classes like integer and string, but you can also create your own class. You do this by simply typing the keyword 'class' (in lowercase) followed by the name you want to give that class:

class Dog:

Instances of a class can have attributes and methods. Attributes are essentially variables assigned to a particular instance - things the object HAS. Eg, 'length', or 'speed'. Methods are just like functions, but specific to classes, and are things the object DOES. Eg, 'bark', or 'move'.

When you create a new class, you specify a special initialize method, stylized as "__init__". Within it, you detail everything that you want to occur whenever a new instance of that class is created.

So for example with the class 'Dog', if we wanted to print "You've created a dog!" to the screen every time a new instance of class Dog was created, we would do that in the __init__ method. In this space, we can also assign any attributes that we want created on the creation of a new instance. So for every Dog object we create, we might want to assign it a name. We would do this with the following syntax:

class Dog:
    def __init__(self, name):
        self.name = name
        print("You've created a dog!")

lassie = Dog("Lassie")
print(lassie.name)

>>> Lassie

Typically when you create methods within a class, you'll always want to include the 'self' parameter, even if there are no other parameters taken. The exception is when you want to create a "static" method, which is a method that doesn't require an instance to be called - you can call it on the class itself. Eg, instead of creating an instance of type Dog like 'Lassie' and typing Lassie.bark(), you can instead just type Dog.bark(). There is also another type of method called a class method that too does not require an instance to be created.