Python Forum
My code displays too much output when importing class from a module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
My code displays too much output when importing class from a module
#1
Hi. This is my first post ever in a Python forum, and I'm a beginner so please bear with me Rolleyes

I have two sets of codes called restaurant.py and test_restaurant.py
My purpose is to use test_restaurant.py to import a class from restaurant.py.
I have made an instance in test_restaurant.py and want to display only the values from this instance. But when I run the code it includes all the other outputs from the module (restaurant.py). Why am I seeing everything and not only what I have specified in my code (test_restaurant.py)?

restaurant.py:
# restaurant.py

class Resto():
    """Building a restaurant code"""

    def __init__(self, restaurant_name, cuisine_type):
        """Initialize name and type attributes."""
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self):
        """prints these two pieces of information"""
        print(self.restaurant_name.title() + " is a " +  self.cuisine_type
              + " restaurant type.")

    def open_restaurant(self):
        """Prints a message that indicates that the restaurant is open."""
        print(self.restaurant_name.title() + " is now open.")

my_resto = Resto('dinner', 'fine dining')
your_resto = Resto('mc donalds', 'fastfood')
their_resto = Resto('alex sushi', 'sushi restau')
our_resto = Resto('big horn', 'steakhouse')

print("I always love to go to " + my_resto.restaurant_name.title() + ".")
print("This type of restaurant is: " + my_resto.cuisine_type + ".")


my_resto.describe_restaurant()
your_resto.describe_restaurant()
their_resto.describe_restaurant()
our_resto.describe_restaurant()
my_resto.open_restaurant()
test_restaurant.py
# Test to import restaurant.py, class Resto()

from restaurant import Resto

my_test = Resto('max burger', 'fastfood')

my_test.describe_restaurant()
I'd be grateful if someone could help me with this beginner challenge Smile
Thanks!
Yoriz write Oct-21-2022, 08:58 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
None of this code should be in restaurant.py
my_resto = Resto('dinner', 'fine dining')
your_resto = Resto('mc donalds', 'fastfood')
their_resto = Resto('alex sushi', 'sushi restau')
our_resto = Resto('big horn', 'steakhouse')

print("I always love to go to " + my_resto.restaurant_name.title() + ".")
print("This type of restaurant is: " + my_resto.cuisine_type + ".")

my_resto.describe_restaurant()
your_resto.describe_restaurant()
their_resto.describe_restaurant()
our_resto.describe_restaurant()
my_resto.open_restaurant()
But maybe this should be:
def main():
    my_resto = Resto('dinner', 'fine dining')
    your_resto = Resto('mc donalds', 'fastfood')
    their_resto = Resto('alex sushi', 'sushi restau')
    our_resto = Resto('big horn', 'steakhouse')

    print("I always love to go to " + my_resto.restaurant_name.title() + ".")
    print("This type of restaurant is: " + my_resto.cuisine_type + ".")

    my_resto.describe_restaurant()
    your_resto.describe_restaurant()
    their_resto.describe_restaurant()
    our_resto.describe_restaurant()
    my_resto.open_restaurant()

if __name__ == "__main__":
    main()
When Python imports a module it executes the code. This is how your class gets defined. But this is also how all those instances are created and all the printing is done. If you don't want that, put the code inside a function and only call the function if the file is the main file (the program you are running).

Next time wrap your code in python tags please.
lil_e likes this post
Reply
#3
When you import Resto all lines of code are carried out.
if you only want some of the lines to happen when directly being used you can use
if __name__ == "__main__":
Here is your code modified with that addition
class Resto():
    """Building a restaurant code"""
 
    def __init__(self, restaurant_name, cuisine_type):
        """Initialize name and type attributes."""
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type
 
    def describe_restaurant(self):
        """prints these two pieces of information"""
        print(self.restaurant_name.title() + " is a " +  self.cuisine_type
              + " restaurant type.")
 
    def open_restaurant(self):
        """Prints a message that indicates that the restaurant is open."""
        print(self.restaurant_name.title() + " is now open.")

def main():
    my_resto = Resto('dinner', 'fine dining')
    your_resto = Resto('mc donalds', 'fastfood')
    their_resto = Resto('alex sushi', 'sushi restau')
    our_resto = Resto('big horn', 'steakhouse')
    
    print("I always love to go to " + my_resto.restaurant_name.title() + ".")
    print("This type of restaurant is: " + my_resto.cuisine_type + ".")
    
    
    my_resto.describe_restaurant()
    your_resto.describe_restaurant()
    their_resto.describe_restaurant()
    our_resto.describe_restaurant()
    my_resto.open_restaurant()


if __name__ == "__main__":
    main()
lil_e likes this post
Reply
#4
Thank you for fast reply! Appreciate it. It was very helpful Smile
Reply
#5
Take a look at the test routine for for my CreateDict class (just happens to be a resturant application):
import os

class CreateDict:
    """
    Generic Software tools used by Trailmapper.

    CreateDict.py - Contains methods to simplify node and cell creation within
                    a dictionary

    Usage: 
    
        The best way to learn what can be done is to examine the testit function
        included in this module.

        new_dict(dictname) - Creates a new dictionary instance with the name
            contained in dictname

        add_node(parent, nodename) - Creates a new node (nested dictionary)
            named in nodename, in parent dictionary.

        add_cell(nodename, cellname, value) - Creates a leaf node within node
            named in nodename, with a cell name of cellname, and value of value.

        display_dict(dictname) - Recursively displays a nested dictionary.

    Requirements:

        Trailmapper software:
            None

        Python standard library:
            os
    
    Author: Larz60+ -- May 2019.
    """
    def __init__(self):
        os.chdir(os.path.abspath(os.path.dirname(__file__)))

    def new_dict(self, dictname):
        setattr(self, dictname, {})

    def add_node(self, parent, nodename):
        node = parent[nodename] = {}
        return node

    def add_cell(self, nodename, cellname, value):
        cell =  nodename[cellname] = value
        return cell

    def display_dict(self, dictname, level=0):
        indent = " " * (4 * level)
        for key, value in dictname.items():
            if isinstance(value, dict):
                print(f'\n{indent}{key}')
                level += 1
                self.display_dict(value, level)
            else:
                print(f'{indent}{key}: {value}')
            if level > 0:
                level -= 1


def testit():
    # instantiate class
    cd = CreateDict()

    # create new dictionary named CityList
    cd.new_dict('CityList')

    # add node Boston
    boston = cd.add_node(cd.CityList, 'Boston')
    # add sub node Resturants
    bos_resturants = cd.add_node(boston, 'Resturants')

    # Add subnode 'Spoke Wine Bar' to parent bos_resturants
    spoke = cd.add_node(bos_resturants, 'Spoke Wine Bar')
    cd.add_cell(spoke, 'Addr1', '89 Holland St')
    cd.add_cell(spoke, 'City', 'Sommerville')
    cd.add_cell(spoke, 'Addr1', '02144')
    cd.add_cell(spoke, 'Phone', '617-718-9463')

    # Add subnode 'Highland Kitchen' to parent bos_resturants
    highland = cd.add_node(bos_resturants, 'Highland Kitchen')
    cd.add_cell(highland, 'Addr1', '150 Highland Ave')
    cd.add_cell(highland, 'City', 'Sommerville')
    cd.add_cell(highland, 'ZipCode', '02144')
    cd.add_cell(highland, 'Phone', '617-625-1131')

    # display dictionary
    print(f'\nCityList Dictionary')
    cd.display_dict(cd.CityList)
    print(f'\nraw data: {cd.CityList}')


if __name__ == '__main__':
    testit()
Here's what you get from the restaurant display,
Output:
CityList Dictionary Boston Resturants Spoke Wine Bar Addr1: 02144 City: Sommerville Phone: 617-718-9463 Highland Kitchen Addr1: 150 Highland Ave City: Sommerville ZipCode: 02144 Phone: 617-625-1131 raw data: {'Boston': {'Resturants': {'Spoke Wine Bar': {'Addr1': '02144', 'City': 'Sommerville', 'Phone': '617-718-9463'}, 'Highland Kitchen': {'Addr1': '150 Highland Ave', 'City': 'Sommerville', 'ZipCode': '02144', 'Phone': '617-625-1131'}}}}
note all of the restauant data is saved in the dictionary and can be saved to a json file by adding (after all current code in testit):
First add this to top of testit():
    import json
then this to bottom of testit()
    with open('myjsonfilename', 'w') as fp:
        json.dump(CityList, fp)
The json part is untested but I think it's correct.

Note:The test routine, was just that. The concept is good, byt to really be useful, there should be methods for sdding a resturant, rather than using inline code.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How does this code create a class? Pedroski55 6 442 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  problem in output of a snippet code akbarza 2 388 Feb-28-2024, 07:15 PM
Last Post: deanhystad
  importing variables from module 8376459 1 289 Feb-18-2024, 02:24 PM
Last Post: deanhystad
  no module named 'docx' when importing docx MaartenRo 1 895 Dec-31-2023, 11:21 AM
Last Post: deanhystad
  How to read module/class from list of strings? popular_dog 1 486 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  Some help with my first python class and importing ....im making a lidar program jttolleson 7 1,221 Jul-28-2023, 08:34 AM
Last Post: jttolleson
  I cannot able to see output of this code ted 1 763 Feb-22-2023, 09:43 PM
Last Post: deanhystad
  New2Python: Help with Importing/Mapping Image Src to Image Code in File CluelessITguy 0 729 Nov-17-2022, 04:46 PM
Last Post: CluelessITguy
  How to run code again in module ? rajamani 2 914 Nov-10-2022, 02:38 PM
Last Post: snippsat
  why I dont get any output from this code William369 2 1,138 Jun-23-2022, 09:18 PM
Last Post: William369

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020