Define a Simple Object

PythonPythonBeginner
Practice Now

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

Introduction

Objectives:

  • Review of how to define a simple object

Files Created: stock.py


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/BasicConceptsGroup -.-> python/python_shell("`Python Shell`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132394{{"`Define a Simple Object`"}} python/tuples -.-> lab-132394{{"`Define a Simple Object`"}} python/function_definition -.-> lab-132394{{"`Define a Simple Object`"}} python/classes_objects -.-> lab-132394{{"`Define a Simple Object`"}} python/constructor -.-> lab-132394{{"`Define a Simple Object`"}} python/polymorphism -.-> lab-132394{{"`Define a Simple Object`"}} python/encapsulation -.-> lab-132394{{"`Define a Simple Object`"}} python/python_shell -.-> lab-132394{{"`Define a Simple Object`"}} python/build_in_functions -.-> lab-132394{{"`Define a Simple Object`"}} end

Defining a simple object

Create a file stock.py and define the following class:

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

Once you have done this, run your program and experiment with your new Stock object:

Note: To do this, you might have to run python using the -i option. For example:

python3 -i stock.py
>>> s = Stock('GOOG',100,490.10)
>>> s.name
'GOOG'
>>> s.shares
100
>>> s.price
490.1
>>> s.cost()
49010.0
>>> print('%10s %10d %10.2f' % (s.name, s.shares, s.price))
      GOOG        100     490.10
>>> t = Stock('IBM', 50, 91.5)
>>> t.cost()
4575.0
>>>

Summary

Congratulations! You have completed the Define a Simple Object lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like