473,551 Members | 2,693 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to use __str__ and __repr__?

hi all, does anyone know what print does if there is no __str__ method?
i'm trying ot override the __repr__. If anyone can give me some advice
it would be great to have.

I have defined a lisp-like linked list class as a subclass of list.
The __iter__ seems to work as i'd like, by traversing the links,
and the __repr__ seems to work properly for somethings but not others.

The basic idea is that a list such as [ 1, 2, 3, 4] is converted to
[1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element
non-destructively onto the beginning of the list; e.g.

x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]]
y = x.cons(2) --> [ 2, [3, [4, [5, nil]]]
z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]]

for elt in z: # iterates elt=1, elt=2, elt=3 ...
pass

I would love to know how to define the __repr__ or __str__
method so that it is able to print everything the way print
normally works, except that instances of my class gets printed
special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]]
simple as a space seperated list. It works most of the time.
--> ( 1 2 3 4 5)

Another question is whether there is a way to promote an
empty list [] to an instance of Pair?

class Pair(list):

def __iter__(self):
while self:
yield self.car()
self = self.cdr()

def __repr__(self):
middle = " ".join( [ substr.__str__( ) for substr in self])
return "( " + middle + " )"

# x = (cons x l_y)
# ==> x = l_y.cons(x)
def cons(self, car):
new = Pair()
new.append(car)
new.append(self )
return new

def car(self):
if self:
return self[0]
return nil

def cdr(self):
if len(self)<2:
return nil
return self[1]

nil = Pair()
# [ 1, 2, 3] --> [1, [2, [3, nil]]]
def seq2pair(seq):
new = Pair()
for index in xrange( len(seq), 0, -1):
new = new.cons(seq[index - 1])
return new

mylist = seq2pair( [1,2,3,4,5])
print mylist # correctly prints --> ( 1 2 3 4 5)
mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist])
print mylist2
# correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) )

class another:
pass

print another() # prints --> <__main__.anoth er instance at 0x8132b64>

# ??????????????? ??????????????? ??????????
print seq2pair( [ another(), another() ]) # FAILS
# ??????????????? ??????????????? ??????????

Traceback (most recent call last):
File "xyz.py", line 52, in ?
print seq2pair( [ another(), another() ])
File "xyz.py", line 13, in __repr__
return "( " + " ".join( [ substr.__str__( ) for substr in self]) + " )"
AttributeError: another instance has no attribute '__str__'

Jul 18 '05 #1
15 5931
Jim Newton wrote:
hi all, does anyone know what print does if there is no __str__ method?


From the documentation at http://docs.python.org/ref/customization.html :

__repr__( self)

Called by the repr() built-in function and by string conversions
(reverse quotes) to compute the ``official'' string representation of an
object. .... If a class defines __repr__() but not __str__(), then
__repr__() is also used when an ``informal'' string representation of
instances of that class is required.

Does that help?
Jul 18 '05 #2
I don't understand what you are trying to do, but
the problem is that when you define class 'another'
the following line doesn't make sense:

middle = " ".join( [ substr.__str__( ) for substr in self])

The instance of another doesn't have a __str__ method
defined (e.g. it's an empty class). All of your other
tests have a class that does have a __str__ method
because it was inherited from the baseclass list.

You could try:

class another(list):
pass

Larry Bates
Syscon, Inc.

"Jim Newton" <ji***@rdrop.co m> wrote in message
news:2i******** ****@uni-berlin.de...
hi all, does anyone know what print does if there is no __str__ method?
i'm trying ot override the __repr__. If anyone can give me some advice
it would be great to have.

I have defined a lisp-like linked list class as a subclass of list.
The __iter__ seems to work as i'd like, by traversing the links,
and the __repr__ seems to work properly for somethings but not others.

The basic idea is that a list such as [ 1, 2, 3, 4] is converted to
[1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element
non-destructively onto the beginning of the list; e.g.

x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]]
y = x.cons(2) --> [ 2, [3, [4, [5, nil]]]
z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]]

for elt in z: # iterates elt=1, elt=2, elt=3 ...
pass

I would love to know how to define the __repr__ or __str__
method so that it is able to print everything the way print
normally works, except that instances of my class gets printed
special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]]
simple as a space seperated list. It works most of the time.
--> ( 1 2 3 4 5)

Another question is whether there is a way to promote an
empty list [] to an instance of Pair?

class Pair(list):

def __iter__(self):
while self:
yield self.car()
self = self.cdr()

def __repr__(self):
middle = " ".join( [ substr.__str__( ) for substr in self])
return "( " + middle + " )"

# x = (cons x l_y)
# ==> x = l_y.cons(x)
def cons(self, car):
new = Pair()
new.append(car)
new.append(self )
return new

def car(self):
if self:
return self[0]
return nil

def cdr(self):
if len(self)<2:
return nil
return self[1]

nil = Pair()
# [ 1, 2, 3] --> [1, [2, [3, nil]]]
def seq2pair(seq):
new = Pair()
for index in xrange( len(seq), 0, -1):
new = new.cons(seq[index - 1])
return new

mylist = seq2pair( [1,2,3,4,5])
print mylist # correctly prints --> ( 1 2 3 4 5)
mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist])
print mylist2
# correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) )

class another:
pass

print another() # prints --> <__main__.anoth er instance at 0x8132b64>

# ??????????????? ??????????????? ??????????
print seq2pair( [ another(), another() ]) # FAILS
# ??????????????? ??????????????? ??????????

Traceback (most recent call last):
File "xyz.py", line 52, in ?
print seq2pair( [ another(), another() ])
File "xyz.py", line 13, in __repr__
return "( " + " ".join( [ substr.__str__( ) for substr in self]) + " )" AttributeError: another instance has no attribute '__str__'

Jul 18 '05 #3
thanks for responding,
i was expecting class().__str__ ()
to evaluate to the string "<__main__.anot her instance at 0x8132b64>"
because that what print does with class().
but alas it does not.

why does print class() not give me the same error as class().__str__ ()?
that's what i do not understand.

-jim
Larry Bates wrote:
I don't understand what you are trying to do, but
the problem is that when you define class 'another'
the following line doesn't make sense:

middle = " ".join( [ substr.__str__( ) for substr in self])

The instance of another doesn't have a __str__ method
defined (e.g. it's an empty class). All of your other
tests have a class that does have a __str__ method
because it was inherited from the baseclass list.

You could try:

class another(list):
pass

Larry Bates
Syscon, Inc.

"Jim Newton" <ji***@rdrop.co m> wrote in message
news:2i******** ****@uni-berlin.de...
hi all, does anyone know what print does if there is no __str__ method?
i'm trying ot override the __repr__. If anyone can give me some advice
it would be great to have.

I have defined a lisp-like linked list class as a subclass of list.
The __iter__ seems to work as i'd like, by traversing the links,
and the __repr__ seems to work properly for somethings but not others.

The basic idea is that a list such as [ 1, 2, 3, 4] is converted to
[1, [2, [3, [4, nil]]], thus allowing me to push (cons) a new element
non-destructively onto the beginning of the list; e.g.

x = seq2pair( [ 3,4,5]) --> [ 3, [4, [5, nil]]]
y = x.cons(2) --> [ 2, [3, [4, [5, nil]]]
z = y.cons(1) --> [ 1, [ 2, [3, [4, [5, nil]]]]

for elt in z: # iterates elt=1, elt=2, elt=3 ...
pass

I would love to know how to define the __repr__ or __str__
method so that it is able to print everything the way print
normally works, except that instances of my class gets printed
special. I want to print [ 1, [ 2, [3, [4, [5, nil]]]]
simple as a space seperated list. It works most of the time.
--> ( 1 2 3 4 5)

Another question is whether there is a way to promote an
empty list [] to an instance of Pair?

class Pair(list):

def __iter__(self):
while self:
yield self.car()
self = self.cdr()

def __repr__(self):
middle = " ".join( [ substr.__str__( ) for substr in self])
return "( " + middle + " )"

# x = (cons x l_y)
# ==> x = l_y.cons(x)
def cons(self, car):
new = Pair()
new.append(car)
new.append(self )
return new

def car(self):
if self:
return self[0]
return nil

def cdr(self):
if len(self)<2:
return nil
return self[1]

nil = Pair()
# [ 1, 2, 3] --> [1, [2, [3, nil]]]
def seq2pair(seq):
new = Pair()
for index in xrange( len(seq), 0, -1):
new = new.cons(seq[index - 1])
return new

mylist = seq2pair( [1,2,3,4,5])
print mylist # correctly prints --> ( 1 2 3 4 5)
mylist2 = seq2pair( [11.1, 21.1, 31.1, 41.1, mylist])
print mylist2
# correctly prints --> ( 11.1 21.1 31.1 41.1 ( 1 2 3 4 5 ) )

class another:
pass

print another() # prints --> <__main__.anoth er instance at 0x8132b64>

# ??????????????? ??????????????? ??????????
print seq2pair( [ another(), another() ]) # FAILS
# ??????????????? ??????????????? ??????????

Traceback (most recent call last):
File "xyz.py", line 52, in ?
print seq2pair( [ another(), another() ])
File "xyz.py", line 13, in __repr__
return "( " + " ".join( [ substr.__str__( ) for substr in self]) +


" )"
AttributeErro r: another instance has no attribute '__str__'



Jul 18 '05 #4
i read that in the documenation. and i assumed from that that
print another()
actually prints the string returned from another().__str __()
and thus __str__ must be being inherited from the superclass
of another, but apparently print does something different.

why does print another() actually print something rather than
complaining that there is no __str__ defined?

-jim
Peter Hansen wrote:
Jim Newton wrote:
hi all, does anyone know what print does if there is no __str__ method?

From the documentation at http://docs.python.org/ref/customization.html :

__repr__( self)

Called by the repr() built-in function and by string conversions
(reverse quotes) to compute the ``official'' string representation of an
object. .... If a class defines __repr__() but not __str__(), then
__repr__() is also used when an ``informal'' string representation of
instances of that class is required.

Does that help?


Jul 18 '05 #5
Jim Newton wrote:
thanks for responding,
i was expecting class().__str__ ()
to evaluate to the string "<__main__.anot her instance at 0x8132b64>"
because that what print does with class().
but alas it does not.

why does print class() not give me the same error as
class().__str__ ()?
that's what i do not understand.


In the example you gave, your class is derived from list, so it uses
list.__str__. It's doing exactly what an object-oriented system should
do; defer to the base class. Why do you think that's wrong?

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ Whoever contends with the great sheds his own blood.
-- Sa'di
Jul 18 '05 #6
Jim Newton wrote:
i read that in the documenation. and i assumed from that that
print another()
actually prints the string returned from another().__str __()
and thus __str__ must be being inherited from the superclass
of another, but apparently print does something different.

why does print another() actually print something rather than
complaining that there is no __str__ defined?


I believe print basically calls str(obj) on the object, and
str() is a builtin which (I believe) basically tries to call
__str__() and if that is not defined, calls __repr__(). If
__repr__ is not defined, it probably defers to a standard
representation based on the id() of the object, which is
always defined.

Not sure what else you're trying to do (I haven't read your
full post) but I believe this and some thought should answer
for pretty much everything you're seeing.

Note that you should probably never call __str__() directly,
but call the str() builtin instead. Same for __repr__()
versus the repr() builtin.

-Peter
Jul 18 '05 #7
if that is the case then why does the following fail

class another:
pass

another.__str__ ()

I would think that would return a string such as
"<__main__.anot her instance at 0x8132b64>"
but it does not seem to.
Erik Max Francis wrote:
Jim Newton wrote:

thanks for responding,
i was expecting class().__str__ ()
to evaluate to the string "<__main__.anot her instance at 0x8132b64>"
because that what print does with class().
but alas it does not.

why does print class() not give me the same error as
class().__str __()?
that's what i do not understand.

In the example you gave, your class is derived from list, so it uses
list.__str__. It's doing exactly what an object-oriented system should
do; defer to the base class. Why do you think that's wrong?


Jul 18 '05 #8
hmm, even when i change it to calling str() rather than __str__()
it does not work.

class another:
pass

print another() # works
another().str() # does not work

does anyone know why?

-jim

Peter Hansen wrote:
Jim Newton wrote:
i read that in the documenation. and i assumed from that that
print another()
actually prints the string returned from another().__str __()
and thus __str__ must be being inherited from the superclass
of another, but apparently print does something different.

why does print another() actually print something rather than
complaining that there is no __str__ defined?

I believe print basically calls str(obj) on the object, and
str() is a builtin which (I believe) basically tries to call
__str__() and if that is not defined, calls __repr__(). If
__repr__ is not defined, it probably defers to a standard
representation based on the id() of the object, which is
always defined.

Not sure what else you're trying to do (I haven't read your
full post) but I believe this and some thought should answer
for pretty much everything you're seeing.

Note that you should probably never call __str__() directly,
but call the str() builtin instead. Same for __repr__()
versus the repr() builtin.

-Peter


Jul 18 '05 #9
Jim Newton wrote:
hmm, even when i change it to calling str() rather than __str__()
it does not work.

class another:
pass

print another() # works
another().str() # does not work

does anyone know why?


str is a function, not a method.

str(another())
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1815
by: Dan Sommers | last post by:
Hi, I have a class whose objects represent physical quantities including uncertainties and units, and I would like more control over the way they print. I have a __str__ method which outputs the quantity and its uncertainty, properly rounded (i.e. the uncertainty to one digit and the quantity to the same precision as the uncertainty),...
15
2920
by: Jan Danielsson | last post by:
Sorry, but I Just Don't Get It. I did search the 'net, I did read the FAQ, but I'm too dumb to understand. As far as I can gather, __str__ is just a representation of the object. For instance: class ServerConnection: def __str__(self): buf = "Server: " + self.name + "\n" buf += "Sent bytes: " + str(self.sentBytes) + "\n"
7
1903
by: Jeffrey E. Forcier | last post by:
I am attempting to write a class whose string representation changes in response to external stimuli. While that effect is obviously possible via other means, I attempted this method first and was surprised when it didn't work, so I now want to know why :) Given the following class definition: class MyClass(object): def Edit(self):
1
1472
by: Edward C. Jones | last post by:
#! /usr/bin/env python class A(list): def __init__(self, alist, n): list.__init__(self, alist) self.n = n def __str__(self): return 'AS(%s, %i)' % (list.__str__(self), self.n)
5
2462
by: Mike Krell | last post by:
I'm running into problems trying to override __str__ on the path class from Jason Orendorff's path module (http://www.jorendorff.com/articles/python/path/src/path.py). My first attempt to do this was as follows: ''' class NormPath(path): def __str__(self): return 'overridden __str__: ' + path.__str__(self.normpath())
6
1252
by: [david] | last post by:
returns poorly formatted values: '13.3' ''
5
5045
by: Konstantinos Pachopoulos | last post by:
Hi, i have the following class: =========================================== class CmterIDCmts: def __init__(self,commiterID,commits): self.commiterID_=long(commiterID) self.commits_=long(commits) def __str__(self):
0
7565
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7492
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8002
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7847
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6106
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3534
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3520
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1097
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.