>>> class Test: ... def __repr__(self): ... return "Test()" ... def __str__(self): ... return "member of Test" ... >>> t = Test() >>> t Test() >>> print(t) member of Test
The __str__
method is what gets called happens when you print it, and the __repr__
method is what happens when you use the repr()
function (or when you look at it with the interactive prompt).
If no __str__
method is given, Python will print the result of __repr__
instead. If you define __str__
but not __repr__
, Python will use what you see above as the __repr__
, but still use __str__
for printing.
Related Posts:
- Creating a static class with no instances
- AttributeError: ” object has no attribute ”
- How can I create an object and add attributes to it?
- Saving and loading objects and using pickle
- Are static class variables possible in Python?
- Does Python have “private” variables in classes?
- How can I flush the output of the print function?
- Python calling method in class
- Difference between ‘cls’ and ‘self’ in Python classes?
- AttributeError: ‘datetime’ module has no attribute ‘strptime’
- How do you call an instance of a class in Python?
- List attributes of an object [duplicate]
- How to extend a class in python?
- How to implement a binary search tree in Python?
- How can I print variable and string on same line in Python?
- Using __add__ operator with multiple arguments in Python
- Python function overloading
- Printing variables in Python 3.4
- Easy pretty printing of floats?
- super() fails with error: TypeError “argument 1 must be type, not classobj” when parent does not inherit from object
- Python dictionary from an object’s fields
- How do I determine the size of an object in Python?
- Accessing a class’ member variables in Python?
- In python, how can I print lines that do NOT contain a certain string, rather than print lines which DO contain a certain string:
- Using print() (the function version) in Python2.x
- How to change the order of DataFrame columns?
- What does %s mean in a python format string?
- ImportError: No module named ‘tensorflow.python’
- How to access environment variable values
- python numpy ValueError: operands could not be broadcast together with shapes
- error: command ‘gcc’ failed with exit status 1 while installing eventlet
- Python foreach equivalent
- Python NoneType object is not callable (beginner)
- _tkinter.TclError: no display name and no $DISPLAY environment variable
- What does if __name__ == “__main__”: do?
- How to fix IndexError: invalid index to scalar variable
- How to write inline if statement for print?
- Could not install packages due to a “Environment error :[error 13]: permission denied : ‘usr/local/bin/f2py'”
- How does numpy.newaxis work and when to use it?
- How to move a file in Python?
- TypeError: cannot unpack non-iterable int objec
- Why are Python’s ‘private’ methods not actually private?
- Pandas DataFrame column to list
- Error: ” ‘dict’ object has no attribute ‘iteritems’ “
- Rename Pandas DataFrame Index
- How to upgrade pip3?
- Is module __file__ attribute absolute or relative?
- Python: How do I make a subclass from a superclass?
- How do I convert a list of ascii values to a string in python?
- Why do I get a “referenced before assignment” error when assigning to a global variable in a function?
- Is there a way to perform “if” in python’s lambda?
- Remove the first character of a string
- Difference in output with waitKey(0) and waitKey(1)
- Overcome ValueError for empty array
- Python list directory, subdirectory, and files
- Parsing boolean values with argparse
- Running Jupyter via command line on Windows
- Using Pip to install packages to Anaconda Environment
- What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?
- How to get all subsets of a set? (powerset)
- Python throws ValueError: list.remove(x): x not in list
- ‘int’ object has no attribute ‘__getitem__’
- Selecting/excluding sets of columns in pandas
- How to add title to seaborn boxplot
- Pygame mouse clicking detection
- How to check the version of scipy
- How to check if type of a variable is string?
- How to print colored text to the terminal
- Understanding NumPy’s einsum
- For loop and ‘numpy.float64’ object is not iterable error
- Difference between two dates in Python
- ImportError: No module named win32com.client
- Error message “Linter pylint is not installed”
- AttributeError: ‘Tensor’ object has no attribute ‘_keras_history’
- pip install -r requirements.txt [Errno 2] No such file or directory: ‘requirements.txt’
- Zsh: Conda/Pip installs command not found
- Find the nth occurrence of substring in a string
- What is the quickest way to HTTP GET in Python?
- Pandas index column title or name
- Removing nan values from an array
- Python – While-Loop until list is empty
- ImportError: No module named xgboost
- How to properly create a HeatMap with Bokeh
- How to detect key presses?
- NaN loss when training regression network
- Building multi-regression model throws error: `Pandas data cast to numpy dtype of object. Check input data with np.asarray(data).`
- TypeError: ‘set’ object does not support indexing
- How do I merge lists in python? [duplicate]
- creating a reverse method for a python list from scratch
- What does on_delete do on Django models?
- Convert floats to ints in Pandas?
- Unable to import tweepy module
- pandas comparison raises TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
- NameError: name ‘python’ is not defined
- How can I recover the return value of a function passed to multiprocessing.Process?
- Python Remove last char from string and return it
- NameError: name ‘reduce’ is not defined in Python
- numpy : calculate the derivative of the softmax function
- Difference between exit(0) and exit(1) in Python
- IOError: [Errno 32] Broken pipe when piping: `prog.py | othercmd`