Define a Class and Create an Instance
In this step, you will learn how to define a basic class and create an object, or instance, from it.
In Object-Oriented Programming, a class is a blueprint for creating objects. It defines a set of attributes (data) and methods (functions) that the created objects will have. An object is an instance of a class, a concrete entity built from the class blueprint.
Let's start by creating a simple Dog class.
First, open the dog.py file from the file explorer on the left side of the WebIDE. This file is currently empty.
Now, add the following code to dog.py to define the Dog class, create an instance, and use it:
## Define a simple Dog class
class Dog:
## Class attribute
species = "Canis familiaris"
## Method
def bark(self):
print("Woof!")
## Create an instance (object) of the Dog class
my_dog = Dog()
## Access the class attribute using the instance
print(f"The species is: {my_dog.species}")
## Call the instance's method
print("The dog says:")
my_dog.bark()
Let's break down the code:
class Dog:: This line defines a new class named Dog.
species = "Canis familiaris": This is a class attribute. Its value is shared among all instances of the Dog class.
def bark(self):: This defines a method, which is a function inside a class. The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class.
my_dog = Dog(): This line creates a new instance of the Dog class and assigns it to the variable my_dog.
my_dog.species: We access the species attribute of the my_dog object using dot notation.
my_dog.bark(): We call the bark method on the my_dog object. Python automatically passes the my_dog object as the self argument to the method.
Save the file. To run your script, open a terminal in the WebIDE and execute the following command:
python dog.py
You should see the following output, confirming that your object was created and its attribute and method were accessed correctly.
The species is: Canis familiaris
The dog says:
Woof!