Define a Simple Object

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to define a simple Python class to represent stock information. Classes are a key concept in object-oriented programming, enabling you to model real - world entities and structure your code more efficiently.

The objectives of this lab include learning to define a simple Python class, understanding class attributes and methods, creating and interacting with class instances, and applying formatting to display object information. The file stock.py will be created during this lab.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 97% completion rate. It has received a 100% positive review rate from learners.

Understanding Python Classes

In Python, a class serves as a blueprint for creating objects. Object-oriented programming is a powerful approach that enables us to organize our code effectively. It does this by grouping related data and functions together. This way, we can manage complex programs more easily and make our code more modular and maintainable.

A Python class is made up of two main components:

  • Attributes: These are variables that store data within a class. Think of attributes as the characteristics or properties of an object. For example, if we are creating a class to represent a person, attributes could be the person's name, age, and height.
  • Methods: These are functions that belong to a class and can access or modify its attributes. Methods define the actions that an object can perform. Using the person class example, a method could be a function that calculates the person's age in months.

Classes are extremely useful as they provide a way to create reusable code and model real-world concepts. In this lab, we will create a Stock class. This class will be used to represent stock information such as the name of the stock, the number of shares, and the price per share.

Here is the basic structure of a Python class:

class ClassName:
    def __init__(self, parameter1, parameter2):
        self.attribute1 = parameter1
        self.attribute2 = parameter2

    def method_name(self):
        ## Code that uses the attributes
        return result

The __init__ method is a special method in Python classes. It is called automatically when we create a new object from the class. This method is used to initialize the object's attributes. The self parameter is a reference to the instance of the class. It is used to access attributes and methods from within the class. When we call a method on an object, Python automatically passes the object itself as the first argument, which is why we use self in the method definitions. This allows us to work with the specific instance's attributes and perform operations on them.

Creating the Stock Class

In Python, a class is a blueprint for creating objects. It allows you to bundle data and functionality together. Now, let's create our Stock class to represent stock information. A stock has certain characteristics, such as its name, the number of shares, and the price per share. We will define attributes for these aspects within our class.

  1. First, you need to be in the correct directory in the WebIDE. If you're not already in the /home/labex/project directory, navigate to it. This is where we'll be working on our Stock class code.

  2. Once you're in the right directory, create a new file in the editor. Name this file stock.py. This file will hold the code for our Stock class.

  3. Now, let's add the code to define the Stock class. Copy and paste the following code into the stock.py file:

class Stock:
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

    def cost(self):
        return self.shares * self.price

In this code:

  • The class Stock: statement creates a new class named Stock. This is like a template for creating stock objects.
  • The __init__ method is a special method in Python classes. It is called a constructor. When you create a new object of the Stock class, the __init__ method will run automatically. It takes three parameters: name, shares, and price. These parameters represent the information about the stock.
  • Inside the __init__ method, we use self to refer to the instance of the class. We store the values of the parameters as instance attributes. For example, self.name = name stores the name parameter as an attribute of the object.
  • The cost() method is a custom method we defined. It calculates the total cost of the stock by multiplying the number of shares (self.shares) by the price per share (self.price).
  1. After adding the code, save the file. You can do this by pressing Ctrl+S or clicking the Save icon. Saving the file ensures that your changes are preserved.

Let's examine the code again to make sure we understand it:

  • We defined a class named Stock. This class will be used to create stock objects.
  • The __init__ method takes three parameters: name, shares, and price. It initializes the object's attributes with these values.
  • Inside __init__, we store these parameters as instance attributes using self. This allows each object to have its own set of values for these attributes.
  • We added a cost() method that calculates the total cost by multiplying shares by price. This is a useful functionality for our stock objects.

When we create a Stock object, the __init__ method will run automatically, setting up the initial state of our object with the values we provide. This way, we can easily create multiple stock objects with different names, numbers of shares, and prices.

Creating Stock Objects

Now that we have defined our Stock class, it's time to put it into action. Creating instances of a class is like making specific examples based on a general blueprint. In this case, the Stock class is our blueprint, and we'll create some stock objects. After creating these objects, we'll learn how to access their attributes (characteristics) and methods (actions they can perform).

  1. First, we need to open a terminal in the WebIDE. The terminal is like a command - center where we can give instructions to our computer. To open it, click on "Terminal" in the menu.

  2. Once the terminal is open, we need to make sure we are in the correct project directory. The project directory is where all the relevant files for our project are stored. If you are not already in the project directory, use the following command to navigate there:

cd /home/labex/project
  1. Now, we want to start Python in interactive mode with our stock.py file. Interactive mode allows us to test our code step - by - step and see the results immediately. The stock.py file contains the definition of our Stock class. Use the following command:
python3 -i stock.py

The -i flag is important here. It tells Python to run the stock.py script first. After running the script, it starts an interactive session. In this session, we can access any classes and variables that were defined in the stock.py script.

  1. Let's create a new Stock object for Google stock. Creating an object is like making a specific instance of the Stock class with particular values. Use the following code:
s = Stock('GOOG', 100, 490.10)

This line of code creates a new instance of the Stock class. Here's what each value means:

  • Name: 'GOOG' - This is the symbol for Google stock.
  • Shares: 100 - It represents the number of shares of Google stock we have.
  • Price: 490.10 - This is the price per share of Google stock.
  1. Now that we have our Stock object, we can access its attributes. Attributes are like the properties of an object. To access an attribute, we use the object's name followed by a dot and the attribute name.
s.name

When you run this code, it will output the name of the stock:

'GOOG'

Let's access the number of shares:

s.shares

The output will be the number of shares we defined:

100

Finally, let's access the price per share:

s.price

The output will be the price per share:

490.1
  1. Our Stock class has a method called cost(). A method is like an action that an object can perform. In this case, the cost() method calculates the total cost of our shares. To call this method, use the following code:
s.cost()

The output will be the total cost:

49010.0

The cost() method works by multiplying the number of shares (100) by the price per share (490.10), which gives us 49010.0.

Working with Multiple Stock Objects

In object - oriented programming, a class is like a blueprint, and instances of that class are the actual objects created based on that blueprint. Our Stock class is a blueprint for representing stocks. We can create multiple instances of this Stock class to represent different stocks. Each instance will have its own set of attributes, such as the stock name, the number of shares, and the price per share.

  1. With the Python interactive session still running, we are going to create another Stock object. This time, it will represent IBM. To create an instance of the Stock class, we call the class name as if it were a function and pass in the necessary arguments. The arguments here are the stock name, the number of shares, and the price per share.
t = Stock('IBM', 50, 91.5)

In this line of code, we are creating a new Stock object named t that represents IBM. It has 50 shares, and each share costs $91.5.

  1. Now, we want to calculate the cost of this new stock. The Stock class has a method named cost() that calculates the total cost of the stock by multiplying the number of shares by the price per share.
t.cost()

When you run this code, Python will call the cost() method on the t object and return the total cost.

Output:

4575.0
  1. We can format and display our stock information in a nice, organized way using Python's string formatting. String formatting allows us to specify how different types of data should be presented in a string.
print('%10s %10d %10.2f' % (s.name, s.shares, s.price))

In this code, we are using the old - style string formatting in Python. The % operator is used to substitute values into a string template. The string template '%10s %10d %10.2f' defines how the stock name, number of shares, and price should be formatted.

Output:

      GOOG        100     490.10

This formatted string works as follows:

  • %10s formats a string in a field 10 characters wide (right - aligned). This means that the stock name will be placed in a space that is 10 characters wide, and it will be right - aligned within that space.
  • %10d formats an integer in a field 10 characters wide. So, the number of shares will be placed in a 10 - character - wide space.
  • %10.2f formats a float with 2 decimal places in a field 10 characters wide. The price will be shown with two decimal places and placed in a 10 - character - wide space.
  1. Now, let's format the IBM stock information in the same way. We just need to replace the object name from s to t in the string formatting code.
print('%10s %10d %10.2f' % (t.name, t.shares, t.price))

Output:

       IBM         50      91.50
  1. In modern Python, we can also use f - strings for formatting. F - strings are more readable and easier to use. Let's compare the costs of both stocks using f - strings.
print(f"Google stock costs ${s.cost()}, IBM stock costs ${t.cost()}")

In this f - string, we are directly embedding expressions inside curly braces {}. Python will evaluate these expressions and insert the results into the string.

Output:

Google stock costs $49010.0, IBM stock costs $4575.0
  1. When you are finished experimenting, it's time to exit the Python interactive mode. You can do this by using the exit() function.
exit()

Each Stock object maintains its own set of attributes, which demonstrates how class instances work in object - oriented programming. This allows us to create multiple stock objects, each with different values, while sharing the same methods.

Enhancing the Stock Class

In Python, classes are a powerful way to organize data and behavior. They allow us to group related data and functions together. In this section, we'll enhance our Stock class by adding a method that displays formatted stock information. This is a great example of how we can encapsulate both data and behavior in our classes. Encapsulation means bundling data with the methods that operate on that data, which helps in keeping our code organized and easier to manage.

  1. First, you need to open the stock.py file in the WebIDE editor. The stock.py file is where we've been working on our Stock class. Opening it in the editor allows us to make changes to the class definition.

  2. Now, we'll modify the Stock class to add a new display() method. This method will be responsible for printing out the stock information in a nicely formatted way. Here's how you can do it:

class Stock:
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

    def cost(self):
        return self.shares * self.price

    def display(self):
        print(f"Stock: {self.name}, Shares: {self.shares}, Price: ${self.price:.2f}, Total Cost: ${self.cost():.2f}")

In the __init__ method, we initialize the stock's name, the number of shares, and the price. The cost method calculates the total cost of the stock by multiplying the number of shares by the price. The new display method uses an f-string to format and print the stock information, including the name, number of shares, price, and total cost.

  1. After making these changes, you need to save the file. You can do this by pressing Ctrl+S on your keyboard or by clicking the Save icon in the editor. Saving the file ensures that your changes are preserved and can be used later.

  2. Next, we'll start a new Python interactive session. An interactive session allows us to test our code immediately. To start the session, run the following command in the terminal:

python3 -i stock.py

The -i option tells Python to start an interactive session after executing the stock.py file. This way, we can use the Stock class and its methods right away.

  1. Now, let's create a stock object and use the new display() method. We'll create an object representing Apple stock and then call the display method to see the formatted information. Here's the code:
apple = Stock('AAPL', 200, 154.50)
apple.display()

When you run this code in the interactive session, you'll see the following output:

Stock: AAPL, Shares: 200, Price: $154.50, Total Cost: $30900.00

This output shows that the display method is working correctly and is formatting the stock information as expected.

  1. Finally, let's create a list of stocks and display them all. This will show how we can use the display method with multiple stock objects. Here's the code:
stocks = [
    Stock('GOOG', 100, 490.10),
    Stock('IBM', 50, 91.50),
    Stock('AAPL', 200, 154.50)
]

for stock in stocks:
    stock.display()

When you run this code, you'll get the following output:

Stock: GOOG, Shares: 100, Price: $490.10, Total Cost: $49010.00
Stock: IBM, Shares: 50, Price: $91.50, Total Cost: $4575.00
Stock: AAPL, Shares: 200, Price: $154.50, Total Cost: $30900.00

By adding the display() method to our class, we have encapsulated the formatting logic within the class itself. This makes our code more organized and easier to maintain. If we need to change the way the stock information is displayed, we only need to modify the display method in one place, rather than making changes throughout our code.

Summary

In this lab, you have learned how to define a Python class with attributes and methods, create class instances with specific attribute values, access object attributes, and call object methods. You also learned to format and display object information in various ways, work with multiple objects of the same class, and enhance a class by adding new methods.

These object - oriented programming concepts are fundamental in Python and serve as the basis for organizing code in larger applications. Classes help group related data and functionality, making your code more modular and easier to maintain. To further improve your skills, consider adding features to the Stock class, such as data validation, methods to update shares or price, and a method to calculate profit or loss.