开发者

Is there a "best" way to do something in Python

I'm just starting getting into Python - my focus being on usi开发者_如何学Gong it with Maya and its API - and I've found that when I'm working on something there's, generally, at least 2 or 3 ways to do the same thing that I'm trying to do. For instance:

for key, value in locNameConnector.iteritems():
    value = locNameConnector[key]
    cmds.connectJoint(value, key, pm=True)

or

for name in locNameConnector:
    cmds.connectJoint(locNameConnector[name][0], name, pm=True)

now the code is calling specific things in Maya, but my question is, which way is more correct? I feel like the first one is because it's taking advantage of Python's power, while the second one could be written in any language. Is there a more correct way? Is one faster than the other?


One of Python's philosophies is:

There should be one -- and preferably only one -- obvious way to do it.

(You can see a list of these - known as The Zen of Python - by doing import this in the Python shell.)

And Python does try and make it so that there really is only one way. But for any language beyond a very basic level of functionality, though, there is always going to be more than one way to do anything non-trivial - that's simply the way programming is. But even when there is more than one way, there is usually one that's regarded as more 'Pythonic'.

As regards your actual examples, they don't seem to be equivalent - the first one is looking up value in l_LegJointConnectors, the second looks it up in locNameConnector. Is that second line in the first example supposed to be there? If not, the first one is very definitely more Pythonic than the second.


There is usually more than one way that fulfills the specification, but often only one correct way. This is in fact the central design principle of Python (as opposed to, say, Perl). In your example, when you need key–value pairs instead of only keys or only values, use iteritems.


I follow the principal "Anything that works is good". Asking yourself -which way would suite me/my code/the application best is more than enough.
But hardcore-python-programmers get very angry if they see any python code which is not "pythonic". A good read for that is here.


Your question is quite vague.It definitely depends on what you want to do but there rarely is ever only one way to do something generally and same applies to python. There are ways of doing things that people would refer to as pythonic though that is subjective and depends on who is looking at the code. Read up zen of python by Tim Peters a renowned pythonista and author of timsort in the standard library to get an idea of some nice ways to write python code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜