Language: EN

como-usar-objetos-python

What are and how to use objects in Python

Object Oriented Programming is a programming paradigm based on the concept of “objects”, which represent real-world entities with their own characteristics (attributes) and behaviors (methods).

In OOP, objects interact with each other through messages, allowing for a more natural way to model complex systems.

If you want to learn more about object-oriented programming, I leave you the link to the Object Oriented Programming Course.

Defining a Class in Python

A class is a template or a “mold” to create objects. It defines the properties and behaviors that objects created from it will have.

In Python, classes are defined with the keyword class followed by the class name and a colon (:).

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")
  • The __init__ method is a special method called a “constructor”, which is automatically executed when a new object of the class is created. Here we initialize the name and age attributes.

  • The greet method is an instance method that shows a greeting with the person’s name and age.

Attributes

Attributes are variables that belong to an object and represent its characteristics or properties. They can be of any data type, such as numbers, strings, lists, etc. In the previous example, name and age are attributes of the person object.

Methods

Methods are functions that belong to an object and can operate on its attributes. They can perform operations, modify the values of the attributes, or interact with other objects. In the example, greet is a method of the person object.

Creating Instances

An instance is each of the “instances” that we create from a class. Each instance will have its own values for the attributes defined in the class.

To create an object from a class, simply call the class name followed by parentheses.

For example, once we have the Person class, we can create instances of this class like this,

john = Person("John", 30)

In this case, we have created a john object from the Person class, with the values “John” for the name attribute and 30 for the age attribute.

Accessing Attributes and Methods

To access both the attributes or methods of an instance, simply use the dot access operator . on the variable containing the instance.

For example like this,

john = Person("John", 30)
anna = Person("Anna", 25)

john.age = 35;  # We change John's age to 35
anna.age = 28;   # We change Anna's age to 28

john.greet()  # Output: Hello, my name is John and I am 35 years old.
anna.greet()   # Output: Hello, my name is Anna and I am 28 years old.