Modules -> OOP -> Classes and objects -> Creating a class

Creating a class


What is a class

A class is a blueprint, like a model or a factory, from which we can later create objects, real things based on that blueprint.

Think of it like this:

  • A class is the idea of a dog.
  • An object is a real dog, like your pet, Murki.

How to create a class

In Python, we create a class using the class keyword, followed by a space, the name of the class, a colon

Everything that belongs to the class must be written four spaces to the right (that's called indentation).

Let's create a simple class to represent a dog. For now, we'll just add a docstring inside it, a short description of what the class is for.

class Dog:
    """Represents a dog."""

Naming Rules for Classes
  • Use English letters, numbers, and underscores.
  • The name can't start with a number.
  • The convention is to use CapitalCamelCase, like Dog, MyClass, or SuperHero.

Exercises

Which of these are valid Python class names by convention?

 MyCar
 Person
 my_person
 person_1



Write a class, Cat with a one-line docstring: "Represents a cat."




Write a class, Car.




Write a class that represents animals.




Write a class that represents a tree.



class Company:
    """Represents a company."""

What is the name of the defined class in the script above?




Exercises

Which of these are valid Python class names by convention?

 animal_list
 Animal
 ShoppingCart
 3DModel



Write a class, Book with a one-line docstring, "Represents a book."




Write a class, Person.




Write a class that represents planets.




Write a class that represents a chair.



class School:
    """Represents a school."""

What is the name of the defined class in the script above?