Rishik Mani
Rishik Mani

Reputation: 498

Python: Variable not defined in external class

I have the following code. Although, the problem is very simple but I cannot figure out the reason behind it.

The following is my main.py:

from model_MNIST import Model

def main():
    model = Model()

if __name__ == '__main__':
    main()

And the model_MNIST.py file is as follows:

# some import statements
class Model(object):
    def __init__(self, input_dimensions, output_dimensions):
        # some init statements

    def train_on_data(self, training_data, training_labels):
        N = training_labels.size

Whenever the class initialization is called I get an output as name 'training_labels' is not defined. This is preventing the execution of the program. Can someone point me out what I might be missing?

Edit1: Please refer to the shared link for the file. SharedFolder

Upvotes: 0

Views: 134

Answers (3)

ergesto
ergesto

Reputation: 397

You need to change this Model.train_on_data(X_train, y_train) to model.train_on_data(X_train, y_train) in main_MNIST.py, in simple .py file https://pastebin.com/JZArvWC3

Upvotes: 0

quamrana
quamrana

Reputation: 39354

This is a summary of the code from your link:

# some import statements
class Model(object):
    def __init__(self, input_dimensions, output_dimensions):
        # some init statements

    def train_on_data(self, training_data, training_labels):
        '''
        Multiline comment
        '''
    N = training_labels.size
    ...

In the above code the last line is part of the class, not the train_on_data method.

I think the last line (and the others elided) should be indented to be part of that method.

Upvotes: 1

mb0850
mb0850

Reputation: 593

From the shared code, what I can understand that you have confused with class and instance variables.

In the function train_on_data, you have some codes like self.training_labels = training_labels but your init method doesn't contain the self.training_labels variable.

Upvotes: 0

Related Questions