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), followed by the units (mostly)
as they accumulated during whatever calculations led to the quantity's
current value. Inside this method, I round the floating point values
appropriately and depend on '%s' to do the Right Thing with the floating
point numbers.
I have a __repr__ method that outputs the three parts in such a way that
eval( repr( v ) ) returns a quantity as equal to v as possible.
I would like to add some other options, e.g., an SI mode that prints the
numbers and units according to SI guidelines, and a LaTeX option that
prints something I can copy and paste into a LaTeX document that uses
the SIunits and/or SIstyle packages and/or my own related macros.
So my question is: Is there a way to pass options "through" a format
string to the __str__ and __repr__ functions? For example, can I define
my own alternate form for use with the '#' formatting character, so that
'%#s' generates output according to SI guidelines?
I know I can always write the formatting methods separately and call
them explicitly, but IMO that's not as clean as using the format control
codes. A collection of "set output format" methods is possible, but
that solution makes me cringe.
Thank you,
Dan
--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn. 3 1823
Dan Sommers wrote: So my question is: Is there a way to pass options "through" a format string to the __str__ and __repr__ functions? For example, can I define my own alternate form for use with the '#' formatting character, so that '%#s' generates output according to SI guidelines?
You can create your own class FmtTemplate like string.Template was done
in python 2.4: http://docs.python.org/lib/node105.html
and have it call obj.__str__("#s ") when you use ${obj:#s} format. I'm
not sure why you want to pass format to repr (as far as I understand
repr is mostly for debug purposes) but you can call from template as
${obj:r} --> obj.__repr__()
${obj:#r} --> obj.__repr__("# r")
fmt = FmtTemplate("qu antity1: ${q1:#s}, quantity2: ${q2:#s}")
q1=MyQuantity(. ..)
q2=MyQuantity(. ..)
print fmt.substitute( q1=q1,q2=q2)
Serge.
On 18 Feb 2005 01:25:06 -0800,
"Serge Orlov" <Se*********@gm ail.com> wrote: Dan Sommers wrote:
So my question is: Is there a way to pass options "through" a format string to the __str__ and __repr__ functions? For example, can I define my own alternate form for use with the '#' formatting character, so that '%#s' generates output according to SI guidelines?
You can create your own class FmtTemplate like string.Template was done in python 2.4: http://docs.python.org/lib/node105.html
That looks interesting. Perhaps that will push me into upgrading to 2.4
sooner rather than later (I'm *not* looking forward to rebuilding all my
extensions...).
Thanks you,
Dan
--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Never play leapfrog with a unicorn.
Dan Sommers wrote: On 18 Feb 2005 01:25:06 -0800, "Serge Orlov" <Se*********@gm ail.com> wrote:
Dan Sommers wrote:
So my question is: Is there a way to pass options "through" a format string to the __str__ and __repr__ functions? For example, can I define my own alternate form for use with the '#' formatting character, so that '%#s' generates output according to SI guidelines?
You can create your own class FmtTemplate like string.Template was done in python 2.4: http://docs.python.org/lib/node105.html
That looks interesting. Perhaps that will push me into upgrading to 2.4 sooner rather than later (I'm *not* looking forward to rebuilding all my extensions...).
You don't need to upgrade to Python 2.4. string.Template is a pure
Python code (about 130 lines) and it looks like it's Python 2.2
compatible. My suggestion was to grab it and hack it to add the
feature you want and then keep it in your own library.
Serge. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jim Newton |
last post by:
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 is converted to
]],...
|
by: could ildg |
last post by:
What's the difference between __repr__ and __str__?
When will __repr__ be useful?
|
by: Steve Holden |
last post by:
I was messing about with formatting and realized that the right kind of
object could quite easily tell me exactly what accesses are made to the
mapping in a string % mapping operation. This is a fairly well-known
technique, modified to tell me what keys would need to be present in any
mapping used with the format.
class Everything:
def __init__(self, format="%s", discover=False):
self.names = {}
self.values =
|
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"
|
by: Ben Finney |
last post by:
Howdy all,
The builtin types have __repr__ attributes that return something nice,
that looks like the syntax one would use to create that particular
instance.
The default __repr__ for custom classes show the fully-qualified class
name, and the memory address of the instance.
If I want to implement a __repr__ that's reasonably "nice" to the
| |
by: Mike MacSween |
last post by:
tblCourses one to many to tblEvents.
A course may have an intro workshop (a type of event), a mid course
workshop, a final exam. Or any combination. Or something different in the
future.
At the moment the printed output is usually going to Word. It's turning into
an unholy mess, because I'm having to prepare umpteen different Word
templates, and the queries that drive them, depending on what events a
course has.
|
by: Russ |
last post by:
I'd like to get output formatting for my own classes that mimics the
built-in output formatting. For example,
>>> x = 4.54
>>> print "%4.2f" % x
4.54
In other words, if I substitute a class instance for "x" above, I'd
like to make the format string apply to an element or elements of the
instance. Can I somehow overload the "%" operator for that? Thanks.
|
by: Neil |
last post by:
I posted a few days ago that it seems to me that the Access 2007 rich text
feature does not support: a) full text justification; b) programmatic
manipulation.
I was hoping that someone might know one way or the other whether that was
true or not, or could point me to an article or help text that would. What I
have seen so far online and in Access 2007 help seems to confirm the above.
But that (or at least (b)) seems incredible that it...
|
by: Roc Zhou |
last post by:
Now I have to design a class that overload __getattr__, but after
that, I found the __repr__ have been affected. This is a simple
example model:
#!/usr/bin/env python
class test:
def __init__(self):
self.x = 1
def __getattr__(self, attr_name):
try:
|
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 usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 most users, this new feature is actually very convenient. If you want to control the update process,...
|
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |