What is the purpose of __str__ and __repr__?
我真的不明白在Python中使用的
但我不明白的是,我会在哪里使用它们?
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).
Called by the
str() built-in function and by the print statement to compute the"informal" string representation of an object.
如果您有一个类,那么使用
1 2 3 4 5 6 7 8 9 | def __repr__(self): """Return string representation of a set. This looks like 'Set([<list of elements>])'. """ return self._repr() # __str__ is the same as __repr__ __str__ = __repr__ |
一个你经常使用它们的地方是在一个互动会话中。如果打印一个对象,则会调用它的
1 2 3 4 5 6 | >>> from decimal import Decimal >>> a = Decimal(1.25) >>> print(a) 1.25 <---- this is from __str__ >>> a Decimal('1.25') <---- this is from __repr__ |
对于
蚱蜢,当有疑问的时候,去山上读古文。在它们中,您会发现uu repr_uu()应该:
If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value.
在前面的答案基础上建立和展示更多的例子。如果使用得当,
1 2 | print repr(datetime.now()) #datetime.datetime(2017, 12, 12, 18, 49, 27, 134411) print str(datetime.now()) #2017-12-12 18:49:27.134452 |
1 | x = datetime.datetime(2017, 12, 12, 18, 49, 27, 134411) |
麻木的
1 2 | print repr(np.array([1,2,3,4,5])) #array([1, 2, 3, 4, 5]) print str(np.array([1,2,3,4,5])) #[1 2 3 4 5] |
在numpy中,
1 2 3 4 5 6 7 8 9 10 11 | class Vector3(object): def __init__(self, args): self.x = args[0] self.y = args[1] self.z = args[2] def __str__(self): return"x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z) def __repr__(self): return"Vector3([{0},{1},{2}])".format(self.x, self.y, self.z) |
在本例中,
1 2 3 | v = Vector3([1,2,3]) print str(v) #x: 1, y: 2, z: 3 print repr(v) #Vector3([1,2,3]) |
One thing to keep in mind, if
str isn't defined butrepr ,str will automatically callrepr . So, it's always good to at least definerepr
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Complex: # Constructor def __init__(self, real, imag): self.real = real self.imag = imag #"official" string representation of an object def __repr__(self): return 'Rational(%s, %s)' % (self.real, self.imag) #"informal" string representation of an object (readable) def __str__(self): return '%s + i%s' % (self.real, self.imag) t = Complex(10, 20) print (t) # this is usual way we print the object print (str(t)) # this is str representation of object print (repr(t)) # this is repr representation of object Answers : Rational(10, 20) # usual representation 10 + i20 # str representation Rational(10, 20) # repr representation |
让我们有一个没有
1 2 3 4 5 6 7 8 9 10 | class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay emp1 = Employee('Ivan', 'Smith', 90000) print(emp1) |
当我们打印这个类的实例
1 | <__main__.Employee object at 0x7ff6fc0a0e48> |
这不是很有帮助,当然,如果我们使用它来显示(如HTML),这不是我们想要打印的内容。
所以现在,同一个类,但是使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay def __str__(self): return(f"The employee {self.first} {self.last} earns {self.pay}.") # you can edit this and use any attributes of the class emp2 = Employee('John', 'Williams', 90000) print(emp2) |
现在,我们不再打印有对象,而是得到返回