Link Search Menu Expand Document

Create your classes and objects

Python allows us to create a class in two lines of code using class. The following code creates a Person class. With pass, we indicate that it is an empty class. Later, we will see how to add attributes and methods to our class.

# Create a class
class Person:
    pass

It is important to note that according to Python conventions, classes are named in CamelCase.

Correct:

  • SomeClass βœ…
  • BankAccount βœ…

Incorrect:

  • some_class ❌
  • bankaccount ❌

Now that we have our class, we can create an object of it. To do this, we use the name of the class followed by (). This invokes the constructor of the class. In this case, the constructor does not receive any parameters.

# Create an object
person = Person()

It is important to understand the difference between class and object:

  • The class refers to something generic, in our case, the idea of a person.
  • The object refers to something concrete, in our case, a specific person.
print(Person)
# Output: <class '__main__.Person'>

print(person)
# Output: <__main__.Person object at 0x103030a99d0>.

Using type, we can know the class to which an object belongs.

print(type(person))
# Output: <class '__main__.Person'>

At this point, we have our class, but it is empty. Let us start adding things to it.