Jak działa instrukcja __repr__

0

Witam,

czy ktoś mógłby mi wytłumaczyć, jak działa, co właściwie robi i jak używać funkcji repr ? Wyczytałem tutaj:

http://docs.python.org/2/reference/datamodel.html

object.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.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

Ale szczerze mówiąc niewiele z tego rozumiem, temu zwracam się z prośbą na forum.

Z góry dziękuję.

0

Z tego opisu wynika, że ta funkcja (czy raczej metoda) służy do zamiany obiektu na string podczas debugowania.
Np.: w wyniku otrzymujemy imie_gracza=Patryk;wiek_gracza=1024; pole3=10; inne_pole=512 (...)

1

@Patryk27 - Zimno. Tzn. trochę prawdy w tym jest, zasadniczo repr to ma być bardziej wygadana wersja str - repr ma zwracać informacje o obiekcie a str go konwertować na czytelny dla człowieka napis.

A co robi repr:

>>> repr(4)                           
'4'                                   
>>> (4).__repr__()                    
'4'                                   
>>> repr("asdf")                      
"'asdf'"                              
>>> ("asdf").__repr__()               
"'asdf'"                               
>>> repr({1: 3, "a": "b"})            
"{'a': 'b', 1: 3}"                    
>>> ({1: 3, "a": "b"}).__repr__()     
"{'a': 'b', 1: 3}"                   

Zero magii. repr(x) <==> x.__repr__().

Odnośnie str vs repr (oraz tego czego repl domyślnie używa):

>>> x = 7.0             
>>> x /= 0.3            
>>> x *= 0.3            
>>> x                   
7.000000000000001       
>>> str(x)              
'7.0'                   
>>> repr(x)             
'7.000000000000001'     

1 użytkowników online, w tym zalogowanych: 0, gości: 1