开发者

How to use "class" the word as parameter function calls in python

I am writing an XML generator per my manager's request. For less typings' sake, I decided using ElementTree as parser and SimpleXMLWriter as writer.

The result XML require attributes named "class". e.g.

<Node class="oops"></Node>

As the official tutorial suggested, to write an XML node just use this method:

w.element("meta", name="generator", value="my application 1.0")

So I wrote:

w.element("Node", class="oops")

python fails yawning SyntaxError. Any help?开发者_如何学运维


I guess SimpleXMLWriter developers meant this solution:

w.element("Node", None, {'class': 'oops'})

or

w.element("Node", attrib={'class': 'oops'})


What steveha has written is true. As in any language, keywords can't be used for different purposes.

What you can do, if you must use "class" is this:

w.element("Node", **{'class': 'oops'})


class is a reserved word in Python. You just can't use it for a variable name, any more than you can have a variable called class in C++.

The usual abbreviation for class is either klass or cls.

Here is an official list of reserved words in Python:

http://docs.python.org/reference/lexical_analysis.html#keywords

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜