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

Class definition and instantiation

face Josiah Wang

Now, let’s delve deeper into designing classes, step by step! Please follow along and try it yourself!

Let’s stick with defining a Person class. I have given you the minimum form of a class definition. Quite straightforward!

1
2
class Person:
    pass

Our favourite PEP 8 states that “class names should normally use the CapWords convention”. So name your objects in CamelCase, like YorkshireTerrier or ComputerMonitor.

I am enforcing this strictly for this course. So please use CamelCase for your ClassName. This helps you distinguish between variables and function names (which should both be in lowercase) much better. It is also the convention in most programming languages anyway!

You can now create a new instance of your brand new Person class (although it is not quite useful at the moment!)

1
2
3
4
5
6
class Person:
    pass

manager = Person()
print(manager)
print(isinstance(manager, Person))

The code should output something like <__main__.Person object at 0x7fe70c878c10>. So manager points to the object of class Person at memory location 0x7fe70c878c10. We will talk about __main__ in the next chapter - it will make more sense then!

The built-in isinstance() function (Line 6) will return True if your object is an instance of a given class.

In essence, you have created a new instance of class Person!

Class instantiation