How to Change the String Representation of a Python Class

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.

How can I choose a custom string representation for a class itself (not instances of the class)?

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.

Edit: Python 3 Version

class MC(type):
def __repr__(self):
return 'Wahaha!'

class C(object, metaclass=MC):
pass

print(C)

How to change class representation when the class is a dictionary's key?

The __repr__ method is used to generate the string that dict uses to display the keys. There is no mechanism to modify the key during dict creation or update, and no dict-specific way to modify how the key is displayed.

By default, DummyClass is inheriting its __repr__ method from object, which is what produces the <...> string. Override __repr__ to return a string built from the name attribute.

class DummyClass:

def __init__(self, name):
self.name = name

def __repr__(self):
return f"'{self.name}'"

There was a proposal to create a key-transforming dictionary, but it was rejected. It would have allowed you to write something like

d = TransformDict(lambda x: x.name)
d[obj_1] = ...
d[obj_2] = ...

and the resulting dict would behave as if 'name1' and 'name2' were the keys (while still allowing access to the original keys obj_1 and obj_2 if necessary).

How to replace __str__ for a function

As Joran said:

class NamedFunction:
def __init__(self, name, f):
self.f = f
self.name = name

def __call__(self, *args, **kwargs):
return self.f(*args, **kwargs)

def __str__(self):
return self.name

f = NamedFunction("lambda: 'blah'", lambda: 'blah')
print(f())
print(f)

How to convert string representation of list to a list

>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

ast.literal_eval:

With ast.literal_eval you can safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, and None.



Related Topics



Leave a reply



Submit