Python Forum

Full Version: My class has name error message
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Okay this is the first time I've created a Python class and I'm running into a problem. The debugger says NameError: Instrument is not defined.

I don't see the problem. Here is my code:

class Instrument:
    
    def __init__ (self):
        self.type = "Guitar"
        
    def main():
        instrument = Instrument()
        
        print("My instrument is", instrument)
        
    main()
Is that your actual indentation? It looks like you are creating an instance of the class from the main method within the class. I could see doing that in certain cases, but here it seems very odd. Then you call that method from within the class definition. Definitely odd.

I wouldn't use type as an attribute name, as it can get confused with the built-in type function.

And please post the full text of the error you are getting.
Okay I modified my code and so far it is working. I moved the instance creation out of the main function and into the class definition.

Now all I need to do is figure out how to print "My instrument is guitar".

Here is what I got now:
class Instrument:
    
    def __init__ (self):
        self.type = "Guitar"
        my_instrument = Instrument()
        
    def get_instrument(self):
        return self.type
    
     
    def main():
        print("My instrument is")
          
    main()
Some problem here,also in basic understanding concepts of class(oop).
Don't use type word as it used bye Python.

If think of it so should information about instrument come in from outside,and not be hard coded in class.
This way can eg all band members can use same class.
class Instrument:
    def __init__(self, instrument):
        self.instrument = instrument

    def description(self):
        return f'My instrument is {self.instrument}'
Usage:
>>> player_1 = Instrument('Gutiar')
>>> player_2 = Instrument('Drums')
>>> player_1.instrument
'Gutiar'
>>> player_2.instrument
'Drums'
>>> 
>>> player_1.description()
'My instrument is Gutiar'
>>> player_2.description()
'My instrument is Drums'
A quick look a at __str__ and __repr__,which is useful many times to have in a class.
__str__ could replace description() method.
class Instrument:
    def __init__(self, instrument):
        self.instrument = instrument

    def __str__(self):
        return f'My instrument is {self.instrument}'

    def __repr__(self):
         return f'Instrument({self.instrument!r})'
Usage:
>>> player_1 = Instrument('Gutiar')
>>> player_2 = Instrument('Drums')
>>> 
>>> # print call __str__
>>> print(player_1)
My instrument is Gutiar
>>> 
>>> # only object show __repr__
>>> player_2
Instrument('Drums')