Return type of operator on inherited class

L

looping

Hi,
my question is on this example:

class MyStr(str):
def hello(self):
print 'Hello !'

s1 = MyStr('My string')
s2 = MyStr('My second string')

s1.hello()
s2.hello()

s = s1 + s2

s.hello()
Hello !
Hello !
Traceback (most recent call last):
File "<string>", line 204, in run_nodebug
File "<module1>", line 13, in <module>
AttributeError: 'str' object has no attribute 'hello'

How could I get a type MyStr from the 'plus' (__add__) operation
without overriding it in my class ?
I need to override *every* operator I like to use ?
 
D

Diez B. Roggisch

looping said:
Hi,
my question is on this example:

class MyStr(str):
def hello(self):
print 'Hello !'

s1 = MyStr('My string')
s2 = MyStr('My second string')

s1.hello()
s2.hello()

s = s1 + s2

s.hello()

Hello !
Hello !
Traceback (most recent call last):
File "<string>", line 204, in run_nodebug
File "<module1>", line 13, in <module>
AttributeError: 'str' object has no attribute 'hello'

How could I get a type MyStr from the 'plus' (__add__) operation
without overriding it in my class ?

You can't.
I need to override *every* operator I like to use ?

Yes.

Diez
 
J

James Stroud

looping said:
Hi,
my question is on this example:

class MyStr(str):
def hello(self):
print 'Hello !'

s1 = MyStr('My string')
s2 = MyStr('My second string')

s1.hello()
s2.hello()

s = s1 + s2

s.hello()

Hello !
Hello !
Traceback (most recent call last):
File "<string>", line 204, in run_nodebug
File "<module1>", line 13, in <module>
AttributeError: 'str' object has no attribute 'hello'

How could I get a type MyStr from the 'plus' (__add__) operation
without overriding it in my class ?
I need to override *every* operator I like to use ?

You will not need to override if you

s = MyStr(s1 + s2)

James
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top