Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9130769
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T08:01:21+00:00 2026-06-17T08:01:21+00:00

I am reading the Python Cookbook and they have this program there: class Temperature(object):

  • 0

I am reading the Python Cookbook and they have this program there:

class Temperature(object):
    coefficients = {'c': (1.0, 0.0, -273.15), 'f': (1.8, -273.15, 32.0),
                    'r': (1.8, 0.0, 0.0)}


    def __init__(self, **kwargs):
        # default to absolute (Kelvin) 0, but allow one named argument,
        # with name being k, c, f or r, to use any of the scales
        try:
            name, value = kwargs.popitem( )
        except KeyError:
            # no arguments, so default to k=0
            name, value = 'k', 0
        # error if there are more arguments, or the arg's name is unknown
        if kwargs or name not in 'kcfr':
            kwargs[name] = value             # put it back for diagnosis
            raise TypeError, 'invalid arguments %r' % kwargs
        setattr(self, name, float(value))


    def __getattr__(self, name):
        # maps getting of c, f, r, to computation from k
        try:
            eq = self.coefficients[name]
        except KeyError:
            # unknown name, give error message
            raise AttributeError, name
        return (self.k + eq[1]) * eq[0] + eq[2]


    def __setattr__(self, name, value):
        # maps settings of k, c, f, r, to setting of k; forbids others
        if name in self.coefficients:
            # name is c, f or r -- compute and set k
            eq = self.coefficients[name]
            self.k = (value - eq[2]) / eq[0] - eq[1]
        elif name == 'k':
            # name is k, just set it
            object.__setattr__(self, name, value)
        else:
            # unknown name, give error message
            raise AttributeError, name

    def __str__(self):
        # readable, concise representation as string
        return "%s K" % self.k


    def __repr__(self):
        # detailed, precise representation as string
        return "Temperature(k=%r)" % self.k

I didn’t understand the following – could someone help me to do so?:

  1. what does this function do name, value = kwargs.popitem( )
  2. What does __getattr__ and __setattr__ do. He didn’t used these in the final calling of the program

This was the ouput:

>>> from te import Temperature
>>> t = Temperature(f=70)        # 70 F is...
>>> print t.c                    # ...a bit over 21 C
21.1111111111
>>> t.c = 23                     # 23 C is...
>>> print t.f                    # ...a bit over 73 F
73.4
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T08:01:22+00:00Added an answer on June 17, 2026 at 8:01 am
    • The kwargs.popitem() method removes one (arbitrary) item from the kwargs dictionary and returns that as a (key, value) tuple. This is then assigned to two variables, name and value.

      In this case it means the class takes one keyword argument (one of k, f, c or r) and if you specify more than one it’ll complain (throw a TypeError) after having looked at one of the keyword arguments you passed in.

    • __getattr__ and __setattr__ are special methods used by python when looking up attributes.

      t.c translates to t.__getattr__('c'), and t.c = 23 translates to t.__setattr__('c', 23).

      So, setting one of t.c, t.f or t.r to an integer is routed to the __setattr__ method, which then uses the self.coefficients mapping to calculate and set self.k instead.

      Looking up one of t.c, t.f or t.r is routed to the __getattr__ method, which then returns a value based on the self.coefficients mapping together with the existing value of self.k to give you a temperature in the requested scale.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i'm reading the Gray Hat Python,, i reach for this :: class debugger(): def
I was reading about python functions and saw this code: def happyBirthday(person): print(Happy Birthday
when reading a python ndb api of google app engine, I cam across this
When I first started reading about Python, all of the tutorials have you use
I'm currently reading Dive Into Python by Mark Pilgrim, and have gotten to the
Python 3 really complicated the whole file reading process, when you have a binary
I am reading cpython code for python 3k and I have noticed, that __missing__
Reading some Python (PyQt) code, I came across as follows. @pyqtSignature(QString) def on_findLineEdit_textEdited(self, text):
I was reading the Python docs about classes and came across this paragraph which
I am reading the Python cookbook at the moment and am currently looking at

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.