python-repr()和val()函数,,1. repr()


1. repr() 函数将对象转化为供解释器读取的形式。

语法

以下是 repr() 方法的语法:

repr(object)

参数

object -- 对象。

返回值

返回一个对象的 string 格式。

str和repr都是用来将数字,列表等类型转化为字符串的形式,但不同之处在于str更加类似于C语言中使用printf输出的内容,而repr输出的内容会直接将变量的类型连带着表现出来,从下图可以看出,对明显带有类型标志的变量而言,str和repr的转换具有明显的差别,如long型数字和字符串的‘’符号,而对于并没有非常大区别的记录数据如整型数字,二者并没有太大的差别。

技术分享图片

2. eval(str)函数很强大,官方解释为:将字符串str当成有效的表达式来求值并返回计算结果。所以,结合math当成一个计算器很好用。

eval()函数常见作用有:
1、计算字符串中有效的表达式,并返回结果

>>> eval(‘pow(2,2)‘)4>>> eval(‘2 + 2‘)4>>> eval("n + 4")85
1234567

2、将字符串转成相应的对象(如list、tuple、dict和string之间的转换)

>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]">>> b = eval(a)>>> b[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]>>> a = "{1:‘xx‘,2:‘yy‘}">>> c = eval(a)>>> c{1: ‘xx‘, 2: ‘yy‘}>>> a = "(1,2,3,4)">>> d = eval(a)>>> d(1, 2, 3, 4)
12345678910111213

3、将利用反引号转换的字符串再反转回对象

>>> list1 = [1,2,3,4,5]>>> `list1`‘[1, 2, 3, 4, 5]‘>>> type(`list1`)<type ‘str‘>>>> type(eval(`list1`))<type ‘list‘>>>> a = eval(`list1`)>>> a[1, 2, 3, 4, 5]


e.g. Your task is to define the following two methods for theCoordinateclass:

Add an__eq__method that returns True if coordinates refer to same point in the plane (i.e., have the same x and y coordinate).

Define__repr__, a special method that returns a string that looks like a valid Python expression that could be used to recreate an object with the same value. In other words,eval(repr(c)) == cgiven the definition of__eq__from part 1.

class Coordinate(object):    def __init__(self,x,y):        self.x = x        self.y = y    def getX(self):        # Getter method for a Coordinate object‘s x coordinate.        # Getter methods are better practice than just accessing an attribute directly        return self.x    def getY(self):        # Getter method for a Coordinate object‘s y coordinate        return self.y    def __str__(self):        return ‘<‘ + str(self.getX()) + ‘,‘ + str(self.getY()) + ‘>‘    def __eq__(self, other):        # First make sure `other` is of the same type         assert type(other) == type(self)        # Since `other` is the same type, test if coordinates are equal        return self.getX() == other.getX() and self.getY() == other.getY()    def __repr__(self):        return ‘Coordinate(‘ + str(self.getX()) + ‘,‘ + str(self.getY()) + ‘)‘



Test: equal 1

Output:
> print(c1)<1,-8>> print(c2)<1,-8>> print(c1 == c2)True

Test: equal 2

Output:
> print(c1)<20,20>> print(c2)<20,20>> print(c1 == c2)True

Test: not equal 1

Output:
> print(c1)<-16,-4>> print(c2)<14,20>> print(c1 == c2)False

Test: not equal 2

Output:
> print(c1)<7,13>> print(c2)<-2,-1>> print(c1 == c2)False

Test: repr

Output:
> print(c1)<17,38>> print(repr(c1))Coordinate(17,38)

Test: repr randomized

Output:
> print(c1)<-12,-20>> print(repr(c1))Coordinate(-12,-20)

python-repr()和val()函数

评论关闭