str class inheritance prob?

J

jkazoo

so I’m trying to create a class that inherits from str, but I want to
run some code on the value on object init. this is what I have:


class Path(str):
def __init__( self, path ):
clean = str(path).replace('\\','/')
while clean.find('//') != -1:
clean = clean.replace('//','/')

print 'cleaned on init:\t',clean
self = clean


so clearly the clean variable is what I want value of the string to
be, but that’s decidedly not the case. so running this:

a=Path('path///with\\nasty/////crap_in_it/')
print a


gives me this:

cleaned on init: path/with/nasty/crap_in_it/
path///with\nasty/////crap_in_it/


what gives? what am I doing wrong, and can I do what I’m trying to
here?
thanks.
 
S

s0suk3

so I’m trying to create a class that inherits from str, but I want to
run some code on the value on object init. this is what I have:

class Path(str):
def __init__( self, path ):
clean = str(path).replace('\\','/')
while clean.find('//') != -1:
clean = clean.replace('//','/')

print 'cleaned on init:\t',clean
self = clean

so clearly the clean variable is what I want value of the string to
be, but that’s decidedly not the case. so running this:

a=Path('path///with\\nasty/////crap_in_it/')
print a

gives me this:

cleaned on init: path/with/nasty/crap_in_it/
path///with\nasty/////crap_in_it/

what gives? what am I doing wrong, and can I do what I’m trying to
here?
thanks.

Regardless of the problem you have initializing the class, why do you
need to inherit from str? Actually, why do you even need a class?
Unless you're dealing something more complex that you didn't mention
here, that should be just a simple function.
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
so I’m trying to create a class that inherits from str, but I want to
run some code on the value on object init. this is what I have:

Others already gave you the technical solution (use __new__, not
__init__). A couple remarks still:


1/
class Path(str):
def __init__( self, path ):
clean = str(path).replace('\\','/')
while clean.find('//') != -1:
clean = clean.replace('//','/')

print 'cleaned on init:\t',clean
self = clean

Assigning to self - or to any other local name - only impact the local
namespace, it won't affect the object previously bound to that name.

2/ you may be interested in the existing path module:
http://www.jorendorff.com/articles/python/path/

HTH
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top