1

Problem: I'm having issues calling classes in a program.

I created a program named example.py which has the following code:

class ExampleBase:

"""
This is the ExampleBase class
"""

def __init__(self, company_name="N/A", stock_dict={}):
    """
    class constructor
    """
    self.company_name = company_name
    self.stock_dict = stock_dict     
    return

def __str__(self):
    """
    Prints the company name string
    """        
    str = "The Company name is: %s" %\
        (self.company_name
        )

    return str


def add_purchase(self, addtlSTK):
    """
    Adds item to stock_dict
    """
    self.stock_dict.update(addtlSTK)
    return

I'm attempting to call ExampleBase in another program whose code is:

import example

if __name__ == "__main__":
    a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)}
    b = example.ExampleBase("Bern", a)

2 Answers2

1

The only problem with your code is the wrong indentation of the example.py. The methods must be indented under the class. Also ensure that both python files are in the same folder.

Here is the indented example.py,

class ExampleBase:

    """
    This is the ExampleBase class
    """

    def __init__(self, company_name="N/A", stock_dict={}):
        """
        class constructor
        """
        self.company_name = company_name
        self.stock_dict = stock_dict
        return

    def __str__(self):
        """
        Prints the company name string
        """
        str = "The Company name is: %s" % \
              (self.company_name
               )

        return str


    def add_purchase(self, addtlSTK):
        """
        Adds item to stock_dict
        """
        self.stock_dict.update(addtlSTK)
        return
Jayson Chacko
  • 2,388
  • 1
  • 11
  • 16
0

Ok, after checking the indents the constructor seems to run fine. I'm now trying to do a bit more and its crashing. Here is the code I'm attempting to run:

import example

if __name__ == "__main__":
    a = {"10-01-2014":(10, 11.25), "10-02-2014":(11, 12.25), "10-03-2014":(12, 13.25)}
    b = example.ExampleBase("Bern", a)
    c = {"10-04-2014":(13, 14.25)}
    b.example.ExampleBase.add_purchase(c)
    print(b)

The error i'm seeing now is: AttributeError: 'ExampleBase' object has no attribute 'example'

  • Replace b.example.ExampleBase.add_purchase(c) with b.add_purchase(c). The variable b is an instance of ExampleBase(). Hence you can call methods of it directly. – Jayson Chacko Oct 16 '17 at 04:36
  • That did it! Thank you! Pretty confusing to know when to use the full name and when not from a beginner standpoint, but I'm starting to get the hang of it. – Ilya Josefson Oct 16 '17 at 04:43