This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Classes and attributes

Classes and instances

face Josiah Wang

As a recap, to use a custom function, you will first need to provide a function definition. Then you use your function by calling it.

1
2
3
4
def print_message():
    print("Hello")

print_message()

It is the same with objects. Remember, an object has a type.

You first need a definition for the type. Then you can create an instance of the type.

1
2
3
4
class Person:
    pass

manager = Person()

The definition of a type is generally known as a class. You should think of class as a blueprint or a template. So lines 1-2 give you the class definition for the class Person.

Once you have a blueprint, then you can instantiate a class to create a class instance (line 4). A class instance is just the ‘proper’ way of saying “object”. Class instantiation is basically creating a new object.

As an analogy, a class is the blueprint/plan for a house, and a class instance is a house that is built according to the blueprint.

Class definition and instantiation

Have you wondered why when you use the type() function, it returns class? Now you know! Basically, 3 is an instance of class 'int'. All instances of Python built-in data types are classes.

>>> type(3)
<class 'int'>
>>> type("python")
<class 'str'>

You can use the terms class and type informally to mean the same thing in Python 3. There is a very subtle difference that makes it slightly confusing (a class is an instance of type), but this is not important!

>>> type(3)
<class 'int'>
>>> type(int)
<class 'type'>