每个类都有默认的__repr__, __str__方法,用print 实例时调用类的str方法,直接输出类的实例,调用的是类的repr方法

在命令行界面,不用print命令打印而是直接写变量名,就是用repr方法

用print打印,用str方法

 

自定义一个类,有__str__()方法和__repr__()方法

直接调用调用repr方法,print调用调用str方法

 重写类的repr和str方法,就可以看出两者的区别

>>> class P:

...     def __repr__(self):

...         return "hi repr method"

...     def __str__(self):

...         return "hi str method"

...

>>> p=P()

>>> p

hi repr method

>>> print p

hi str method

>>> 

 

>>> s=1
>>> s
1
>>> print s
1

相关文章:

  • 2021-07-31
  • 2021-12-30
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2021-05-29
  • 2022-12-23
猜你喜欢
  • 2022-01-22
  • 2022-12-23
  • 2021-11-25
  • 2022-01-30
  • 2021-12-30
  • 2021-11-06
  • 2021-11-17
相关资源
相似解决方案