a1letterword
a1letterword

Reputation: 307

Instantiating a class in python with a variable in the Class

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?

Upvotes: 1

Views: 1980

Answers (2)

SudoKid
SudoKid

Reputation: 439

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

Upvotes: 0

zondo
zondo

Reputation: 20366

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.

Upvotes: 1

Related Questions