Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Class Problem
#1
I am trying to create a simple python programme that takes some user input and plots the data. So I decided to use a class to make the programme versatile enough that you can keep calling the class and input new information and plot data. The programme currently asks for the name of a file and identifies if that file is a text or csv file. The programme has some built in tests to determine if the input was valid and asks for the user to input again if an error or incorrect file name is added.

The problem I have is that I want to create another function within the class that you can call that takes the data from the text/csv file and allows you to plot it using the plotting abilities within python. However, after the user has input and the data is extracted from the file I cannot return any of the information into the __init__ part of the class so that it can be used for other functions within the class. I am not sure how to go about correcting this issue or whether my method is too complicated as I am new to python programming and I am not fully competent when using classes in python. Any help will be much appreciated.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

class file_load:
    def __init__(self, name, xdata, ydata):
        self.name = name
        self.xdata = xdata
        self.ydata = ydata
    
    @classmethod
    def user_input(self):
            while True:
                try:
                    name = input('Enter file name')
                    if '.''txt' in name:
                        print('File name: ' + name)
                        data = pd.read_csv(name, delimiter = '\t')
                        print(data.head(10))
                        xdata = data.columns[0]
                        ydata = data.columns[1]
                        break
                    elif '.''csv' in name:
                        print('File name: ' + name)
                        while True:
                            try:
                                data = pd.read_csv(name)
                                xdata = data[data.columns[0]]
                                ydata = data[data.columns[1]]
                                plotting = input('Do you want to plot the data?').lower()
                                if plotting.startswith('y'):
                                    print('PLOTTING')
                                    break
                                elif plotting.startswith('n'):
                                    print('END')
                                    break
                                else:
                                    continue
                            except pd.errors.ParserError:
                                while True:
                                    try:
                                        row = input('Enter data start row')
                                        data = pd.read_csv(name, header = int(row))
                                        print(data.head(10))
                                        xdata = data[data.columns[0]]
                                        ydata = data[data.columns[1]]
                                        break
                                    except pd.errors.ParserError:
                                        print('ERROR: INCORRECT ROW START')
                                        print('Enter data start row: ')
                                        continue
                                break
                            print('ERROR: FILE UNKNOWN')
                            print('Please enter file name:')
                            continue
                except FileNotFoundError:
                    print('ERROR: FILE NOT FOUND')
                    print('Enter file name: ')
                    continue
                break

file_load.user_input()
Reply
#2
A class is a thing, an object. You aren't creating an instance of the class. What you have written is basically a function... code that performs a task.

A simpler approach might be either to have the user input outside the class and the result of that is sent when you create the class,
##all your input stuff here
loaded_file = Loaded_file(name, xdata, ydata) #this will give it all the information 
                                              #when it starts
the other is to use python's return() function.

loaded_file = file_load(name, xdata, ydata)

   ## and have the function return(loaded_file), whatever that may be.
But at a basic level, remember that classes are objects, things. Functions/methods do stuff.

So you either want to make a File_loader class or a file_load function. Either will work, but it has to be clear about what it is.

THIS video is a good introduction to the idea of classes.
Reply
#3
as a side note - consider refactoring user_input method in several smaller methods (some may be for internal use only). This will help you simplify the code, remove repetitive code...
I've split thread to https://python-forum.io/showthread.php?tid=26351
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  class definition and problem with a method HerrAyas 2 255 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  Practice problem using lambda inside the class jagasrik 3 2,170 Sep-12-2020, 03:18 PM
Last Post: deanhystad
  [split] Python Class Problem astral_travel 12 4,987 Apr-29-2020, 07:13 PM
Last Post: michael1789
  Class problem duckduck23 2 2,025 Feb-10-2020, 08:52 PM
Last Post: jefsummers
  Class code problem from CS Dojo YouTube Dixon 3 2,272 Feb-04-2020, 10:23 PM
Last Post: snippsat
  Class Problem scratchmyhead 3 2,324 Nov-19-2019, 08:28 AM
Last Post: Larz60+
  problem with class method AmirAB 3 3,393 Feb-13-2019, 01:51 AM
Last Post: AmirAB
  A problem with child class Truman 2 2,791 Jul-02-2018, 12:37 AM
Last Post: ichabod801
  problem with simple class code diegoraffo 5 3,697 Jan-27-2018, 02:31 AM
Last Post: ka06059
  Converting c++ class to python class panoss 12 11,847 Jul-23-2017, 01:16 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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