Python Basics: Object Oriented Programming (OOP)
Creating Objects
Lesson 2 of 7 • 10 XP
Keep your place in this quest
Log in or sign up for free to subscribe, follow lesson progress, and access more learning content.
Once you’ve defined a class, you can bring it to life by creating objects from it.
Remember: a class is just a blueprint — it doesn’t hold any real data until you create an object (also called an instance) based on it.
How to Create an Object
To create an object from a class, you call the class name like a function, passing in any required parameters for its __init__ method.
Example:
person1 = Person("John", 30)
````
Here’s what happens step-by-step:
1. Python sees `Person("John", 30)` and calls the `__init__` method inside the `Person` class.
2. `"John"` is assigned to the `name` attribute, and `30` is assigned to the `age` attribute for this specific object.
3. A new object is created and stored in the variable `person1`.
TIP: The variable person1 is just a reference to the object in memory — you can have multiple variables pointing to the same object if needed.
---
# Accessing Attributes and Methods
Once you have an object, you can access its **attributes** (data) and **methods** (actions) using **dot notation**.
Example:
```python
print(person1.name) # Output: John
person1.greet() # Output: Hello, my name is John and I am 30 years old.
person1.namegets the value of thenameattribute stored inside the object.person1.greet()calls thegreetmethod, which uses the object’s attributes to display a personalized message.
IMPORTANT!: When calling a method, you must include parentheses () — otherwise, you’re just referencing the method, not executing it.
Creating Multiple Objects
One of the strengths of classes is that you can create as many objects from them as you want, each with its own unique data.
Example:
person2 = Person("Alice", 25)
print(person2.name) # Output: Alice
person2.greet() # Output: Hello, my name is Alice and I am 25 years old.
Here:
person1andperson2are bothPersonobjects, but each has its own state (nameandagevalues).- Methods like
greet()work the same way for both objects, but produce different results based on their attributes.
Wrapping Up
Creating objects is how you bring your classes to life. From a single blueprint, you can create many unique instances, each carrying its own data but sharing the same set of behaviors.
In the next lesson, we’ll explore inheritance — a way to make new classes based on existing ones, reusing and extending their functionality.