__str__ or __repr__ when subclassing System.Object?

Hi all,

I have a question about str (or repr) when subclassing from System.Object in a Grasshopper ghpython component?

if I create a simple class and subclass from System.Object, everything works as expected, including a custom str() output when using a print statement inside the component. BUT if I add that new object to a list and send it out of the component, the str representation in a GH-panel does not show my custom str ?

from System import Object
import random

class My_Class( ): 

    def __init__(self, attr):
        self.id = random.randint(1000,9999)
        self._some_attribute = attr
    
    @property
    def some_attribute(self):
        return self._some_attribute
    
    @some_attribute.setter
    def some_attribute(self, _input):
        self._some_attribute = _input

    def __str__(self):
        return unicode(self).encode('utf-8')
    def __unicode__(self):
        return u'My Object with and ID of: <{}>'.format(self.id)
    def __repr__(self):
        return "{}( attr={!r}".format( self.__class__.__name__, self.attr)

my_object = My_Class(12)

print(my_object)
print('Attribute= ', my_object.some_attribute)
my_object.some_attribute = 57
print('Attribute= ', my_object.some_attribute)

a = []a.append( my_object )

It seems to be showing the System.Object instead? from System import Object

I wonder if there is something special I need to do in order to get my custom str to show up in a panel? When I do NOT subclass from System.Object it seems to work as I had expected:

any thoughts or advice are always appreciated!

thanks,
@ed.p.may

Just an update in case anyone else finds this post in the future and has the same issue, I think one solution to this seems to be to override the ToString() method on the new class with a call to the new str(). I don’t think that breaks anything?

def ToString(self):
    return str(self)

Seems to work for me at least:

@ed.p.may

1 Like