Python equivalent __str __ () method?

In Ruby, is there an equivalent to the __str__() method that can be defined on Python classes?

+4
source share
3 answers
+14
source

FWIW, the check is probably more like __repr__() than __str__()

from the library reference ...

repr (self)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required.

+6
source

In the main classes, he usually "checks."

For instance:

 irb(main):001:0> puts "array is: #{[1,2,3].inspect}" array is: [1, 2, 3] => nil irb(main):002:0> puts "array is: #{[1,2,3]}" array is: 123 => nil irb(main):003:0> 
+4
source

Source: https://habr.com/ru/post/1277180/


All Articles