0

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.

Adam Sirrelle
  • 357
  • 8
  • 18
  • "The pen is blue".replace("blue", "red") – maya Jun 24 '22 at 02:57
  • 1
    You can get your code to work if you make Color a subclass of string i.e. `class Color(str):` Then: ``"The pen is blue".replace(blue, "red")` works. – DarrylG Jun 24 '22 at 03:09
  • @DarrylG, I did not know you could do that! That works for my needs, thank you. Could you put this as the answer, and I'll flag this as resolved. :) – Adam Sirrelle Jun 24 '22 at 03:14

1 Answers1

1

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
DarrylG
  • 16,732
  • 2
  • 17
  • 23