Python Class Polymorphism with Stock Price

Python day 28 

The stock market is going up again today! So let’s construct a simple Python program that generates the stock price range for Tech companies, Banks, and Pharma companies.

Last time we use the Abstract Class to print out multiple song lyrics, today we will level up the difficulties by assigning different computation rules to the corresponding classes.

Rule of Stock Price Range Approximation:

  • Technology company: Stock price varies between 0.8x to 1.25x.

  • Bank: Stock price varies between 0.9x to 1.1x

  • Pharmaceutical: Stock price varies between 0.8x to 1.5x.

Python code:

from abc import ABCMeta, abstractmethod

class Company(object, metaclass=ABCMeta):

    def __init__(self, name):
        self._name = name

    def name(self):
        return self._name

    def get_stock(self):

class Tech(Company):

    def __init__(self, name, p):
    def p(self):
        return self._p
    def p(self,p):
    def get_stock(self):
        return (self._p * 0.8, 1.25*self._p)

class Bank(Company):
    def __init__(self, name, loan):
        self._loan = loan

    def loan(self):
        return self._loan

    def loan(self, loan):
        self._loan = loan 

    def get_stock(self):
        return (self._loan*0.9 , 1.1 *self._loan)
class Phar(Company):

    def __init__(self, name, sales):
        self._sales = sales

    def sales(self):
        return self._sales

    def sales(self, sales):
        self._sales = sales

    def get_stock(self):
        return (self._sales * 0.8, self._sales*1.5)

Call the Stock Price Code

def price():
    emps = [
        Tech('Facebook', 200), Tech('Apple',370),
        Bank("JPMorgan", 99 ), Bank("BAC", 26),
        Phar("Pfizer", 30), Phar("Moderna",70)
    for emp in emps:
        print('The range of %s stock price is %s dollars in 2020 撒花!⊙o⊙' %
              (, emp.get_stock()))


The range of Facebook stock price is (160.0, 250.0) dollars in 2020 撒花!⊙o⊙
The range of Apple stock price is (296.0, 462.5) dollars in 2020 撒花!⊙o⊙
The range of JPMorgan stock price is (59.4, 108.9) dollars in 2020 撒花!⊙o⊙
The range of BAC stock price is (15.6, 28.6) dollars in 2020 撒花!⊙o⊙
The range of Pfizer stock price is (24.0, 45.0) dollars in 2020 撒花!⊙o⊙
The range of Moderna stock price is (56.0, 105.0) dollars in 2020 撒花!⊙o⊙

Note: I checked the stock price and selected a reasonable x to fit the market value, this is NOT accurate stock prices!

Happy Studying and be Rich!




Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social media & sharing icons powered by UltimatelySocial
%d bloggers like this: