开发者

Other uses of the __name__ attribute

开发者 https://www.devze.com 2023-01-28 23:42 出处:网络
I\'m learning Python by reading Dive Into Python online, and in Chapter 2 I see that you can use the __name__ attribute for testing purposes, so I was wondering, does anyone k开发者_如何学Cnows about

I'm learning Python by reading Dive Into Python online, and in Chapter 2 I see that you can use the __name__ attribute for testing purposes, so I was wondering, does anyone k开发者_如何学Cnows about other uses for this attribute? Thanks


I once had a decorator for a command-line script file.

The decorator was used like this:

@command
def someFunc():
    # code goes here

The decorator was doing something like this:

commands = {}
def command(func)
    commands[func.__name__] = func
    return func

And then I could do something like this:

commandName = raw_input()
commands[commandName]();

Which would read a command's name from the console and call it - if it was labeled with the decorator before (so no dangerous calls would be possible as with input).

(In my code the name was taken from the command-line args, not raw_input.)

This easily let me provide commands accessible via their name. That's one of the uses - a general rule would be "it's useful when you want to add your own semantics to the notion of function definition". The same goes for decorators in general.

(BTW, there's func.func_name field, which is more correct to use than func.__name__ because identifiers starting with __ are supposed to be private in Python, AFAIK - just a minor detail)


It can be very useful when debugging. When writing frameworks (or any other highly generic piece of software), you can easily debug using name to know what's being passed around.

0

精彩评论

暂无评论...
验证码 换一张
取 消