Mattman85208
Mattman85208

Reputation: 2090

Python how to use the word class to reference a key 'class'?

Python 3, how do I reference a key named 'class':

print("id: " + eachasset.id)
print("name: " + eachasset.SName)
print("status: " + eachasset.status)
print("class: " + eachasset.class)  # <-- gives me error: Invalid Syntax

Spyder 4 highlights the word class as purple.

Upvotes: 0

Views: 319

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

.something isn't a key, it is an attribute. You cannot use a key-word, like class in an expression some_object.some_attribute since key-words are reserved.

This was likely set dynamically, so your only option is to retrieve it dynamically, so:

getattr(eachasset, 'class')

Or just change the name to class_, as you would conventionally do to name attributes and avoid using a keyword.

Upvotes: 3

Maximouse
Maximouse

Reputation: 4383

You can use getattr():

print("class: " + getattr(eachasset, "class"))

Upvotes: 1

Related Questions