SQLAlchemy: Hybrid Value Object, Query Tuple Results
I am trying to follow the examples from the documentation on building custom comparators using hybrid value objects,
class CaseInsensitiveWord(Comparator):
"Hybrid value representing a lower case representation of a word."
def __init__(self, word):
if isinstance(word, basestring):
开发者_如何学C self.word = word.lower()
elif isinstance(word, CaseInsensitiveWord):
self.word = word.word
else:
self.word = func.lower(word)
def operate(self, op, other):
if not isinstance(other, CaseInsensitiveWord):
other = CaseInsensitiveWord(other)
return op(self.word, other.word)
def __clause_element__(self):
return self.word
def __str__(self):
return self.word
key = 'word'
"Label to apply to Query tuple results"
I don't understand, however, why this was added to the end of the class definition:
key = 'word'
"Label to apply to Query tuple results"
What is this for?
While it's not a fully baked Python feature, a convention is to comment attributes in the same way as functions and methods, i.e. by placing a string below the attribute. Comments like the above are picked up by tools like Sphinx. You can see examples of these docstrings getting generated in places like http://www.sqlalchemy.org/docs/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.class_manager.
edit: oh why it has an actual ".key". When you say:
for row in session.query(MyClass.mycustomthing, MyClass.myothercustomthing):
print row.word, row.someotherword
the "word" and "someotherword" tuple keys are the value of ".key" on each comparator. if you were to call label() on it, that would change it to something else. I don't know that it's strictly necessary to be there at all.
精彩评论