简体   繁体   中英

Why does str + Markup return a Markup object?

With MarkupSafe , which is used in Jinja and Flask, adding a str object and a Markup object returns a Markup object:

>>> from flask import Markup
>>> 'foo' + Markup('bar')
Markup('foobar')

But if I call str.__add__ directly, it returns a str object:

>>> 'foo'.__add__(Markup('bar'))
'foobar'

So it seems that adding str and Markup with + calls Markup.__add__ regardless of the order of the operands. How is this possible?

The + operator calls Markup.__radd__ instead of str.__add__ because the right operand's type ( Markup ) is a subclass of the left operand's type ( str ).

(see Difference between a+b and a.__add__(b) )

When calling str.__add__ on a Markup object, the Markup object is just seen as a str object and the operation is done considering str type only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM