Detailed Explanation of Python Object Oriented Programming repr Method Example
- 2021-12-04 19:10:35
- OfStack
Why do you want to talk about __repr__
In Python, direct print 1 instance object, the default is to output the object created by which class, and the address in memory (106-ary representation)
Assuming that you want to output custom content when you use an print instance object during development and debugging, you can use the __repr__ method
Or calling the object through repr () will also return the value returned by the __repr__ method
Is it deja vu... that's right... and __str__1-like feeling code chestnut
class A:
pass
def __repr__(self):
a = A()
print(a)
print(repr(a))
print(str(a))
# Output result
<__main__.A object at 0x10e6dbcd0>
<__main__.A object at 0x10e6dbcd0>
<__main__.A object at 0x10e6dbcd0>
By default, __repr__ () returns and instances the object < Class name object at memory address > Relevant information
Override __repr__ method
class PoloBlog:
def __init__(self):
self.name = " Small pineapple "
self.add = "https://www.cnblogs.com/poloyy/"
def __repr__(self):
return "test[name=" + self.name + ",add=" + self.add + "]"
blog = PoloBlog()
print(blog)
print(str(blog))
print(repr(blog))
# Output result
test[name= Small pineapple ,add=https://www.cnblogs.com/poloyy/]
test[name= Small pineapple ,add=https://www.cnblogs.com/poloyy/]
test[name= Small pineapple ,add=https://www.cnblogs.com/poloyy/]
Override only the __repr__ method, which will also take effect when using str ()
class PoloBlog:
def __init__(self):
self.name = " Small pineapple "
self.add = "https://www.cnblogs.com/poloyy/"
def __str__(self):
return "test[name=" + self.name + ",add=" + self.add + "]"
blog = PoloBlog()
print(blog)
print(str(blog))
print(repr(blog))
# Output result
test[name= Small pineapple ,add=https://www.cnblogs.com/poloyy/]
test[name= Small pineapple ,add=https://www.cnblogs.com/poloyy/]
<__main__.PoloBlog object at 0x10e2749a0>
If you only override the __str__ method, using repr () will not take effect!
Differences between str () and repr ()
https://www.ofstack.com/article/64333.htm
The above is Python object-oriented programming repr method example details, more about Python object-oriented programming repr information please pay attention to other related articles on this site!