Search code examples
pythonpython-3.xclassdefault-arguments

'name not defined' when setting a class to a variable


Sorry for the dumb question, I can't seem to find the answer anywhere.

I'm trying to convert my class into a variable but it gives me an error

NameError: name 'period' is not defined
class Stuff():
    
    def __init__(self, period = 1, division = 1): 
    
        print(str(period), str(division))
            
stuff = Stuff(period, division)

But I don't understand why it's not defined as I went out of my way to define it as '1' just to be sure.

I get the same error if I don't define the parameters

class Stuff():
    
    def __init__(self, period, division): 
    
        print(str(period), str(division))
            
stuff = Stuff()

I don't want to define the parameters before I call them as the parameters won't have a value until then. Nor do I understand why it needs to be defined because function initiation parameters are not literal.


Solution

  • A few things.

    Firstly, you're not "converting" your class into a variable. You're instantiating type and assigning that instance to a variable, something that holds a reference to an object.

    Moving to the problem at hand. As the comments suggest and extending on that, you're fundamentally misunderstanding default parameters and instantiation.

    In your first example you have period and division parameters which are both defined within the scope of the constructor (__init__). It is valid to use these in the constructor because they exist in that scope.

    Below this you attempt to instantiate Stuff by passing variables called period and division which do not exist. They do not exist because you are outside of the scope of the constructor.

    You need to create these

    class Stuff():
        
        def __init__(self, period = 1, division = 1): 
            print(str(period), str(division))
    
    
    period = 1
    division = 1
    
    stuff = Stuff(period, division)
    

    The defined variables have nothing to do with the parameters of the Stuff class, other than the fact that they are passed in when instantiating this object.

    In your second example you've removed these non-existent variables from the instantiation which is correct but you've also removed the default assignment of the parameters in the Stuff class which is wrong. It's wrong because now you're instantiating an object whose constructor has required parameters, without this it does not know what to do with those parameters.

    The error reflects this mandatory requirement

    TypeError: __init__() missing 2 required positional arguments: 'period' and 'division'
    

    For the second example, the correct syntax would be

    class Stuff():
        
        def __init__(self, period = 1, division = 1):
            print(str(period), str(division))
    
    
    stuff = Stuff()