Skip to content

Some questions on how to use Quantity's as objects #27

Answered by KenKundert
jeffwright13 asked this question in Q&A
Discussion options

You must be logged in to vote

I increasingly find myself subclassing Quantity to support specific and common units. This started when I wanted to print dollar amounts, because the formatting for currency is idiosyncratic. So I would typically define something like this at the top of my code:

    >>> class Dollars(Quantity):
    ...     units = '$'
    ...     form = 'fixed'
    ...     prec = 2
    ...     strip_zeros = False
    ...     show_commas = True

That simplifies printing a dollar amount:

    >>> print(f"Total: {Dollars(total)}")
    $10,000.00

Over time I found myself doing that more and more often. It seems like an approach that might help you. For example, you could create subclasses for types of quantit…

Replies: 1 comment 8 replies

Comment options

You must be logged in to vote
8 replies
@jeffwright13
Comment options

@KenKundert
Comment options

@jeffwright13
Comment options

@KenKundert
Comment options

@jeffwright13
Comment options

Answer selected by jeffwright13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants