How is ndb.StringProperty equals a python string?

喜夏-厌秋 提交于 2020-01-04 05:06:23

问题


I have this ndb Model class

class foo(ndb.Model):
  abc = ndb.StringProperty()

Now when I used abc like this:

if foo.abc == "a":
  print "I'm in!"

It gets into the if block and prints I'm in!

How's this possible?

I also tried printing foo.abc, it returned StringProperty('abc')


回答1:


You have to instantiate an instance of class to use properties properly.

class Foo(ndb.Model):
  abc = ndb.StringProperty()

foo = Foo()
foo.abc = 'some val'
print foo.abc  # prints 'some val'
print foo.abc == 'a' # prints False
print Foo.abc == 'a' # prints something not boolean - can't check now.

You are are getting "I'm in!" because ndb properties are overwriting __equal__ operator and returning a non empty object that is treated as True. This is used to make queries like query.filter(foo.abc == 'def')



来源:https://stackoverflow.com/questions/46545125/how-is-ndb-stringproperty-equals-a-python-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!