== is type isinstance

# a = b = Num(3); c = Num(3); d = Real()
# a == b, a is b       (True, True)
# a == c, a is c       (True, False)
# <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
# 3 == c, 3 is c       (False, False)
# type(a) is Num       True
# type(d) is Num       False
# isinstance(d, Num)   True
class Num():
    def __init__(m, x = 0): m.x = x
    def __eq__(m, x): return isinstance(x, Num) and x.x == m.x
class Real(Num): pass
def eg(x): print(x); exec(x, globals()) #  If only globals is given, locals defaults to it.
def p(x): print(x.ljust(20), eval(x))
eg('a = b = Num(3); c = Num(3); d = Real()')
p('a == b, a is b')
p('a == c, a is c')
p('3 == c, 3 is c')
p('type(a) is Num')
p('type(d) is Num')
p('isinstance(d, Num)')
上一篇:python基础知识


下一篇:025_反射