repr

str() vs repr() functions in python 2.7.5 [duplicate]

你离开我真会死。 提交于 2019-11-26 15:46:24
问题 This question already has an answer here: Difference between __str__ and __repr__? 22 answers what is the difference between str() and repr() functions in python 2.7.5? Explanation on python.org: The str() function is meant to return representations of values which are fairly human-readable , while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax) But it wasn't clear for me. some examples: >>> s =

Accessing Object Memory Address

蓝咒 提交于 2019-11-26 05:55:27
问题 When you call the object.__repr__() method in Python you get something like this back: <__main__.Test object at 0x2aba1c0cf890> Is there any way to get a hold of the memory address if you overload __repr__() , other then calling super(Class, obj).__repr__() and regexing it out? 回答1: The Python manual has this to say about id() : Return the "identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two

Understanding repr( ) function in Python

杀马特。学长 韩版系。学妹 提交于 2019-11-25 22:43:32
问题 repr() : evaluatable string representation of an object (can \"eval()\" it, meaning it is a string representation that evaluates to a Python object) In other words: >>> x = \'foo\' >>> repr(x) \"\'foo\'\" Questions: Why do I get the double quotes when I do repr(x) ? (I don\'t get them when I do str(x) ) Why do I get \'foo\' when I do eval(\"\'foo\'\") and not x which is the object? 回答1: >>> x = 'foo' >>> x 'foo' So the name x is attached to 'foo' string. When you call for example repr(x) the

Why do backslashes appear twice?

十年热恋 提交于 2019-11-25 22:20:53
问题 When I create a string containing backslashes, they get duplicated: >>> my_string = \"why\\does\\it\\happen?\" >>> my_string \'why\\\\does\\\\it\\\\happen?\' Why? 回答1: What you are seeing is the representation of my_string created by its __repr__() method. If you print it, you can see that you've actually got single backslashes, just as you intended: >>> print(my_string) why\does\it\happen? The string below has three characters in it, not four: >>> 'a\\b' 'a\\b' >>> len('a\\b') 3 You can get

Difference between __str__ and __repr__?

早过忘川 提交于 2019-11-25 21:34:52
问题 What is the difference between __str__ and __repr__ in Python? 回答1: Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained objects’ __repr__ Default implementation is useless This is mostly a surprise because Python’s defaults tend to be