Home > OS >  Get a string when running an object class through str.replace(obj_cls, "new string")
Get a string when running an object class through str.replace(obj_cls, "new string")

Time:06-24

I have an object class:

class Color(object):
    def __init__(self, color):
        self.color = color

I want to run the following commands:

blue = Color("blue")

print blue
"The pen is {}".format(blue)
"The pen is blue".replace(blue, "red")

This returns:

# <__main__.Color object at 0x000001A527675908>
# The pen is <__main__.Color object at 0x000001A527675908>

# # Original exception was:
# Traceback (most recent call last):
#   File "<maya console>", line 2, in <module>
# TypeError: expected a string or other character buffer object # 

I can fix the print and format by including repr to the class.

class Color(object):
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return self.color

blue = Color("blue")

print blue
"The pen is {}".format(blue)
"The pen is blue".replace(blue, "red")

# blue
# The pen is blue

# # Original exception was:
# Traceback (most recent call last):
#   File "<maya console>", line 2, in <module>
# TypeError: expected a string or other character buffer object # 

How can I get the replace function to work with this object class?

It works if I put a str() wrapper around the object class:

"The pen is blue".replace(str(blue), "red")

However I don't want to do it this way, as it would require a lot of special code support to function.

CodePudding user response:

A solution is to make your class a subclass of str. This is similar to How to make a class that acts like a string?

Modified Code

class Color(str):
    def __init__(self, color):
        self.color = color

    def __repr__(self):
        return self.color

Usage

blue = Color("blue")
print("The pen is {}".format(blue))
print("The pen is blue".replace(blue, "red"))

Output

The pen is blue
The pen is red
  • Related