Object1=2018
Object2="2018"
id(Object1) >>>2399282764784
id(Object2) >>>2399281922600
type(Object1) >>>int
type(Object2) >>>str
Object1 is Object2 >>>False
a=100
b=1000
# c与a共用id,d另立门户
c=100
d=1000
id(a)==id(c) >>>True
id(b)==id(d) >>>False
__repr__()
和__str__()
的关系了。如你所知,这是Python的两个魔法方法,其对应的内置函数是repr() 和 str()。对于对象x,有x.__repr__()
等价于 repr(x),同理,x.__str__()
等价于 str(x)。repr(2018) >>>'2018'
str(2018) >>>'2018'
repr([1,2,3]) >>>'[1, 2, 3]'
str([1,2,3]) >>>'[1, 2, 3]'
words = "Hello pythonCat!\n"
repr(words) >>>'Hello pythonCat!\n'
str(words) >>>'Hello pythonCat!\n'
# 结合print,注意换行符\n
print(repr(words))
>>>'Hello pythonCat!\n'
print(str(words))
>>>Hello pythonCat! # 再加换行
>>>
__repr__()
和__str__()
方法)的话,其默认的名片就会是类名及内存地址,如下所示。class Person:
def __init__(self,name,sex):
self.name = name
self.sex = sex
me = Person("pythonCat", "male")
repr(me)
>>> '<__main__.Person object at 0x0000022EA8D7ED68>'
str(me)
>>> '<__main__.Person object at 0x0000022EA8D7ED68>'
a = 1 + 1
b = [1, 2, 'cat']
c = {'name':'pythonCat', 'sex':'male'}
eval(repr(a)) >>>2
eval(repr(b)) >>>[1, 2, 'cat']
eval(repr(c)) >>>{'name': 'pythonCat', 'sex': 'male'}
class Person:
def __init__(self,name,sex):
self.name = name
self.sex = sex
# 定制私人名片
def __str__(self):
return "{} is an elegant creature!".format(self.name)
me = Person("pythonCat", "male")
repr(me)
>>>'<__main__.Person object at 0x000002E6845AC390>'
str(me)
>>>'pythonCat is an elegant creature!'
list = [1, 2]
if list: # 即if True
print("list is not empty")
else:
print("list is empty")
>>> list is not empty
True + 1 >>>2
True + 1.0 >>>2.0
False + False >>>0
True + (True*2) >>>3
True/2*5 >>>2.5
type(True) >>> bool
isinstance(True,int) >>>True
isinstance(False,int) >>>True