Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actual value of a subclassed str

Tags:

python

How can I read the inputted value "transform" from the instance of this subclass?

class Str(str):
    def __repr__(self):
        return "mesh"

    def __str__(self):
        return "mesh"

string = Str("transform")
print(string)
# mesh
print(repr(string))
# mesh
like image 754
Marcus Ottosson Avatar asked Nov 27 '25 05:11

Marcus Ottosson


1 Answers

You cannot edit the value. You can retrieve it as a regular string with

str.__str__(string)

using the overridden __str__ method directly.

The C++ binding is most likely reading the string through the Python C API, which goes directly to the underlying storage in the structure your object inherits from str, bypassing the methods you wrote.

As for what you should do, you should get out of this whole situation with subclassing str and overriding __str__. The right way to do that will depend on why you even got yourself into this situation in the first place.

like image 74
user2357112 supports Monica Avatar answered Nov 28 '25 19:11

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!