How to create a custom string representation for a class object?
Implement __str__()
or __repr__()
in the class's metaclass.
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object):
__metaclass__ = MC
print(C)
Use __str__
if you mean a readable stringification, use __repr__
for unambiguous representations.
Custom String representation of an Object in Java
You need to override the toString() method.
@Override
public String toString() {
return "Empty JLabel";
}
How to make the Python str() function work with a custom class?
def __str__(self):
will be used when you try to str(my_object). It would also be called in string interpolation such as f'This is my object: {my_object}'
def __repr__(self):
will be used to represent your object in a console
>>> class A():
... def __str__(self):
... return 'im a string nicely formatted'
... def __repr__(self):
... return 'class A object'
...
>>> a = A()
>>> print(a)
im a string nicely formatted
>>> a
class A object
How to customise the string representation of an object while debugging Python in VS Code
This can be done by overriding the __repr__()
method of the object.
class Person(object):
def __init__(self, name: str, age: int) -> None:
self.name = name
self.age = age
def __repr__(self) -> str:
return f"Person({self.name=}, {self.age=})"
The __repr__()
method is used by VS Code's debugger rather than the __str__()
method, since __str__()
is intended for user-facing representation and __repr__()
is intended for debugging.
How do I change the string representation of a Python class?
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
- Special Method Names - Basic Customization
Change the string representation of a class itself
You need to use meta classes:
class Meta(type):
def __repr__(self):
return "hi"
class Test(metaclass=Meta):
pass
print(Test)
>>> hi
The __repr__
method works on instances not on classes. However in python a class is itself an "instance" of a meta class type
. So if you make a custom meta class with a custom __repr__
method, all classes that are created with your meta class will use your __repr__
method.
Some more reading on meta classes.
String representation of a class in Python 3
What changed is how the metaclass is declared in 3.x.
class C(metaclass=MC):
pass
Swift - How to I define a special method for my class that returns a string representation of its object
Just conform to the CustomStringConvertible
protocol. All you have to do is implement the description
property.
struct Person: CustomStringConvertible {
let name: String
let age: Int
var description: String {
return "[name: \(name), age: \(age)]"
}
}
print(Person(name: "bob", age: 32)) // [name: bob, age: 32]
Custom 'String' Class
Implement a toString
method.
toString
is a method on Object
, so every java object inherits one. The default implementation that you inherit is only useful for getting the class type, and for distinguishing one object from another; the format is: ClassName@HashCode. There are no details unique to your implementation.
In your own classes, to get the description that you want you'll need to override the toString
method, so that in contexts where a String
is expected, e.g. when you call System.out.println(myObject.toString());
, your own format is used.
It's often a good idea to do this, for a more readable description of your object. You can always call super.toString
to include the output from the default - ClassName@HashCode - in your own output.
Related Topics
How to Remove \Xa0 from String in Python
What's the Purpose of "Send" Function on Python Generators
Very Large Matrices Using Python and Numpy
Getting Distance Between Two Points Based on Latitude/Longitude
Differences Between Distribute, Distutils, Setuptools and Distutils2
How to Load Default Profile in Chrome Using Python Selenium Webdriver
Python: Why Is Functools.Partial Necessary
Item Frequency Count in Python
How to Implement an Efficient Bidirectional Hash Table
How to Extract the Decision Rules from Scikit-Learn Decision-Tree
Max Retries Exceeded with Url in Requests
Double Iteration in List Comprehension
How to Get the Named Parameters from a Url Using Flask
Python: Pandas Merge Multiple Dataframes
How to Compare Version Numbers in Python
How to Display Pandas Dataframe of Floats Using a Format String for Columns