1
class Neuralnetwork(data):

    def __init__(self, data):    
         self.data = data

    print(data)



if __name__ == "__main__":
    Neuralnetwork(3)

I was expecting this to output the number 3, but I keep getting error: data not defined. But I thought I defined data when instantiating the class and passing it a value?

1
  • You should either declare the class: class Neuralnetwork: or class Neuralnetwork(object), further, the print statement should be inside the __init__ (fix the identation). Commented Apr 4, 2017 at 0:09

2 Answers 2

1

It is true that you defined the data attribute when you instantiated, but the print line is executed at the class definition, before you instantiate. If you want to print the data, try print(self.data) inside __init__.

Edit: I did not notice at first that you declared your class as class Neuralnetwork(data). That syntax means that you are creating a class that inherits from the data class. Since that class does not exist, you'll have an error. Just remove that and use class Neuralnetwork instead.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I'm green to python, so I have another stupid question. I set up the print statement just to check to make sure that the data variable held something before I went further into creating additional methods and functions. How do I access the variable data? That's why I was trying to print it, just testing how to get to the contents.
When you instantiate the class, assign a variable to it: network = Neuralnetwork(3). You can then access the data as network.data. For example, print(network.data).
Thanks making more sense to me!
0

Your current system has Neuralnetwork inheriting from data. What you are currently trying to do is best done in the __init__ method. You also really shouldn't do a print in the body of a class like this.

Python doesn't have the concept of private methods and function and as such everything can be accessed with dot notation. With that being said adding a _ to the start of a function/method/field will tell the users of your class/library that it should be treated as though it was private.

class Neuralnetwork(object):

    def __init__(self, data):    
         self.data = data

    print(self.data)



if __name__ == "__main__":
    nuralnetwork1 = Neuralnetwork(3)
    print(nuralnetwork1.data) # Prints the number 3 to the console
    nuralnetwork2 = Neuralnetwork(2)
    print(nuralnetwork2.data) # Prints the number 2 to the console
    print(nuralnetwork1.data + nuralnetwork2.data)  # Prints the number 5 to the console

1 Comment

Thanks, but I was really just trying to make sure that the data variable held the information I expected before I went on creating more functions and methods. How do I access that variable otherwise?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.