473,320 Members | 1,883 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

using % operator to print possibly unitialized data attributes

The following code uses the % operator to print possibly unitialized
data attributes:
------------------------8<------------------------
class J:
name = ''
value = ''
def __str__(self):
vals = self.__class__.__dict__
vals.update(self.__dict__)
return 'name="%(name)s" value="%(value)s' % vals

j = J()
j.name = "j object"
print j
------------------------>8------------------------

A couple of questions:
* is there a simpler or more elegant way to do this?
* how can I get this to work for new-style classes?

Thank you,
-Adam

--
Adam Monsen <ha*****@gmail.com>
http://adammonsen.com/

Sep 9 '05 #1
3 1205
Adam Monsen wrote:
class J:
name = ''
value = ''
def __str__(self):
vals = self.__class__.__dict__
vals.update(self.__dict__)
return 'name="%(name)s" value="%(value)s' % vals


This will update the class's attributes with instance attributes when
str() is called, which probably isn't what you want. For instance:
foo = J()
foo.name = "Joe Bloggs"
print foo name="Joe Bloggs" value=" bar = J()
print bar

name="Joe Bloggs" value="

What's wrong with the obvious version:

class J(object):
name = ''
value = ''
def __str__(self):
return 'name=%r value=%r' % (self.name, self.value)
Sep 9 '05 #2
Leif K-Brooks wrote:
This will update the class's attributes with instance attributes
when str() is called, which probably isn't what you want. [...]

Yikes, you're right! Well, I figured out a modification to my original
__str__ code that works for old and new-style classes which doesn't
overwrite the __class__.__dict__:

class J(object):
name = ''
value = ''
def __str__(self):
vals = dict(self.__class__.__dict__)
vals.update(self.__dict__)
return 'name="%(name)s" value="%(value)s' % vals

What's wrong with the obvious version:

[...]

Oh, that looks nice and clean. I like it.

I also found a recipe in the Python cookbook that works great for
"dumping" objects:
http://aspn.activestate.com/ASPN/Coo.../Recipe/137951
(shortened: http://snipurl.com/hka7 )

Thanks!
-Adam

--
Adam Monsen
http://adammonsen.com/

Sep 9 '05 #3
[Adam Monsen]
The following code uses the % operator to print possibly unitialized
data attributes:
------------------------8<------------------------
class J:
name = ''
value = ''
def __str__(self):
vals = self.__class__.__dict__
vals.update(self.__dict__)
return 'name="%(name)s" value="%(value)s' % vals j = J()
j.name = "j object"
print j
------------------------>8------------------------ A couple of questions:
* is there a simpler or more elegant way to do this?
* how can I get this to work for new-style classes?


One solution which I used a few times, and which also opens the way to
many other niceties, is to manage so `vals' is a `dict'-like type of
your own. Then, you write its `__getitem__' method the way you want.

If I remember well, one of the niceties is that whenever `%(EXPR)s'
is used in a format string, EXPR may be a string (well balanced with
regard to parentheses) which you may then choose to "evaluate", for any
definition of "evaluate" which is fruitful for your application. :-)

--
François Pinard http://pinard.progiciels-bpi.ca
Sep 9 '05 #4

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

Similar topics

25
by: Rim | last post by:
Hi, I have been thinking about how to overload the assign operation '='. In many cases, I wanted to provide users of my packages a natural interface to the extended built-in types I created for...
4
by: Michael Sparks | last post by:
Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it...
5
by: Carlos Ribeiro | last post by:
Hello all, I'm posting this to the list with the intention to form a group of people interested in this type of solution. I'm not going to spam the list with it, unless for occasional and...
4
by: Shailesh | last post by:
Hi! I want to overload << operator so that it can print an arry defined in MyClass.My problem is that I want to print only a no of elements NOT all the elements in the array and this no of...
0
by: Michelle Keys | last post by:
I am trying to call a print function to print a string from a database using javascript. Which is RC_DATA of Varchar2(2500). This is a javascript is not being used. I have a thing that needs to...
6
by: Ivan A. Kosarev | last post by:
Hello, Consider the fragment: class C { // A POD-struct public: C() { puts("C::C()"); } }; int main()
0
by: Kamilche | last post by:
''' event.py An event manager using publish/subscribe, and weakrefs. Any function can publish any event without registering it first, and any object can register interest in any event, even...
7
by: fakeprogress | last post by:
For a homework assignment in my Data Structures/C++ class, I have to create the interface and implementation for a class called Book, create objects within the class, and process transactions that...
9
by: chikkubhai | last post by:
Why is the result different for the following set of two code snippets Code without using this pointer #include <string> #include <iostream> using namespace std; struct X { private:
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.