472,782 Members | 1,723 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,782 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 1192
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: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.