Python repr method tutorial for object-oriented programming
This article focuses on the "Python object-oriented programming repr method tutorial", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn the "Python object-oriented programming repr method tutorial"!
Catalogue
Why do you talk about _ _ repr__
Override the _ _ repr__ method
The difference between str () and repr ()
Why do you talk about _ _ repr__
In Python, print an instance object directly. The default is to output the object created by which class and the address in memory (hexadecimal representation).
Assuming that during development and debugging, when you want to use print instance objects and output custom content, 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. Feel the same code as _ _ str__ Chestnut
Class A: pass def _ repr__ (self): a = A () print (a) print (repr (a)) print (str (a)) # output result
By default, _ _ repr__ () returns information about the instance object
Override the _ _ 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= pineapple, add= https://www.cnblogs.com/poloyy/]test[name= pineapple, add= https://www.cnblogs.com/poloyy/]test[name= pineapple, add= https://www.cnblogs.com/poloyy/]
Only override the _ _ repr__ method, which will also take effect when you use str ()
Class PoloBlog: def _ init__ (self): self.name = "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= Little Pineapple Add= https://www.cnblogs.com/poloyy/]test[name= pineapple, add= https://www.cnblogs.com/poloyy/]
If you only override the _ _ str__ method, using repr () won't work!
At this point, I believe you have a deeper understanding of the "Python object-oriented programming repr method tutorial". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!