简体   繁体   中英

Python NameError when defining class

The below Python fails for some reason.

class NetVend:
    def blankCallback(data):
        pass

    def sendCommand(command, callback=NetVend.blankCallback):
        return NetVend.sendSignedCommand(command, NetVend.signCommand(command), callback)

    def sendSignedCommand(command, signature, callback):
        pass

I get the following error:

Traceback (most recent call last):
  File "module.py", line 1, in <module>
    class NetVend:
  File "module.py", line 5, in NetVend
    def sendCommand(command, callback=NetVend.blankCallback):
NameError: name 'NetVend' is not defined

You cannot refer to a class name while still defining it .

The class body is executed as a local namespace; you can refer to functions and attributes as local names instead.

Moreover, default values to function keyword parameters are bound at definition time , not when the method is called. Use None as a sentinel instead.

Instead of:

def sendCommand(command, callback=NetVend.blankCallback):
    return NetVend.sendSignedCommand(command, NetVend.signCommand(command), callback)

use:

def sendCommand(command, callback=None):
    if callback is None:
        callback = NetVend.blankCallback
    return NetVend.sendSignedCommand(command, NetVend.signCommand(command), callback)

You probably wanted to use the class as a factory for instances instead of as a namespace for what are essentially functions. Even if you only used one instance (a singleton) there are benefits in actually creating an instance first.

Well, I wouldn't say the first, but the second option is certainly true :-)

The trouble is that the default argument is evaluated at compile time, but at that point NetVend does not exist in that scope, because (obviously) the class itself has not yet been fully evaluated.

The way round it is to set the default to None, and check within the method:

def sendCommand(command, callback=None):
   if callback is None:
        callback=NetVend.blankCallback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM