Can you set the object class return as a string?
I have tried setting the object class with the __str__
and __repr__
methods overwritten.
class A(object):
def __str__(self):
return "the string"
def __repr__(self):
return "the repr"
a = A()
This works for print statements, and running the class instance directly.
print a
a
the string
# Result: the repr #
However, when trying to set the class instance as a string input, I get this error.
from PySide2 import QtWidgets
QtWidgets.QLabel().setText(a)
# Error: 'PySide2.QtWidgets.QLabel.setText' called with wrong argument types:
# PySide2.QtWidgets.QLabel.setText(A)
# Supported signatures:
# PySide2.QtWidgets.QLabel.setText(unicode)
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# TypeError: 'PySide2.QtWidgets.QLabel.setText' called with wrong argument types:
# PySide2.QtWidgets.QLabel.setText(A)
# Supported signatures:
# PySide2.QtWidgets.QLabel.setText(unicode) #
Is there another method I need to overwrite to get the results I need?
Update
I am limited to using python 2.7 as I am writing tools for versions of Maya that do not use Python 3
I want to avoid wrapping the object class instance:
# Undesired syntax
QtWidgets.QLabel().setText(str(a))
QtWidgets.QLabel().setText(unicode(a))
# Desired syntax
QtWidgets.QLabel().setText(a)
I have tried using a string class, which does return a string when parsing the instance of the class, but you are unable to change the string that the class was first instanced with. eg:
class A(str):
def __str__(self):
return "the string"
def __repr__(self):
return "the repr"
a = A("string")
QtWidgets.QLabel().setText(a)
This will set the text as "string"
, however I have so far been unable to change this string after initialisation. I have tried things like self.__str__.im_self("new string")
, but it never changes the stored variable class data.
I believe this is the same core problem I'm having with the object class, where I am unable to change what is being returned from the stored instance.
Here I found @seeg discussing the same problem when dumping the class to a JSON file, using a Unicode class:
https://stackoverflow.com/a/13489906/3950707
I feel like I need to find whatever core method or attribute is being returned when parsing the instanced class, and amend the str/unicode data there, as this returns a string, but also acts as an object class.
You can change what is returned when parsing the class instance by overwriting the __new__
method, however I have been unsuccessful in achieving my desired results this way, as this only runs when the class is first initialised.
def __new__(cls, *args, **kwargs):
#return str(object.__new__(cls))
return str(super(A, cls).__new__(cls))