repr use the eval function, in fact, eval really pretty good.

Or on the basis of, __ str__ with __repr__ In fact, I have a very long time been confused, they are specific to what purpose.

Today looked back at the previous master teacher instructional videos, combined with knowledge of the book "Inside Python Characteristics". Remarks himself under.

 

The opposite of said first said two relatively small with repr and eval function so simple I do not understand necessarily a long time ago.

eval you simply can restore any object repr returned.

a = 123
a_repr = repr(a)
b = eval(a_repr)
print(a == b)

 Returns true

I did not understand before, repr and str relationship, the feeling is there repr is set above a layer of quotation marks, or strings, why design a repr what to do.

In fact, repr eval generally used in pairs, a pair can be any Python object using repr function (method), the popular understanding I think it can be said with a string preserved, but you can use eval restore them.

class Car:
    def __init__(self, color, mileage):
        self.color = color
        self.mileage = mileage

 

car = Car('red', 123)
cat_repr = repr(car)
car_2 = eval(cat_repr)
print(car_2.color)

 Examples repr can also save and then returns through the object eval. repr Python is an expression which should be the most powerful polymorphic form, because any object has a method, but the method of performing the output of each is different.

eval if the object inside is some logic operations, the value of which can be calculated, very early, I use eval children to do the mental arithmetic form.

eval('1+2')
3
eval('1.2+2')
3.2

 In some foreign materials or primary school textbooks, with eval ( 'specific figures') I think than an int or float more appropriate, eval is actually the initial reduction target of the most primitive state, before also teach their children the best use int or float feeling misleading him.

 

Finally said formatted output in a format! R usage

Format strings from the input if you want to format the state of an object repr, a simple input format will be misinterpreted.

a = '[1,2,3]'
b = [1,2,3]
f'a is {a}, b is {b}'
'a is [1,2,3], b is [1, 2, 3]'

 In the above code, is output from the point of view, can not be seen, like the original state, the initial state of a and b.

a = '[1,2,3]'
b = [1,2,3]
f'a is {a}, b is {b}'
'a is [1,2,3], b is [1, 2, 3]'
f'a is {a !r}, b is {b !r}'
"a is '[1,2,3]', b is [1, 2, 3]"

 However! R & lt output, can clearly tell the difference between a and b, a, after the repr, the outside layer parenthesis, before the object is a list of instructions, and b is obviously previous list.

 

One began to tell the difference between the lower and __repr__ of __str__.

 

Guess you like

Origin www.cnblogs.com/sidianok/p/11922648.html
Recommended