MObject
MObject

Reputation: 397

About class and __str__

I try to return a string value when i print an instance of my class. It seems like that shouldn't work like i wish.

class oObject (object):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return str(self.value)
    def __repr__(self):
        return str(self.value)

new = oObject(50)
# if I use print it's Okay
print new
# But if i try to do something like that ...
print new + '.kine'

Upvotes: 0

Views: 163

Answers (4)

pepr
pepr

Reputation: 20762

Try print new to see that your .__str__() definition works. The print calls it internally. However, the + operator does not use the implicit conversion to string.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838166

Try explicitly converting to a string:

print str(new) + '.kine'

Alternatively you could use a format string:

print '{}.kine'.format(new)

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

override __add__ for it:

class oObject (object):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return str(self.value)
    def __repr__(self):
        return str(self.value)
    def __add__(self,val):
        return str(self.value)+val

new = oObject(50)
'''if I use print it's Okay'''
print new
'''But if i try to do something like that ...'''
print new + '.kine'   #prints 50.kine

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121814

Python converts the result of the whole expression to a string before printing, not individual items. Convert your object instance to a string before concatenating:

print str(new) + '.kine'

Python is a strongly typed language and won't convert items to strings automatically when using operators like the '+' sign.

Upvotes: 2

Related Questions