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?:
- what does this function do
name, value = kwargs.popitem( ) - 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
The
kwargs.popitem()method removes one (arbitrary) item from thekwargsdictionary and returns that as a(key, value)tuple. This is then assigned to two variables,nameandvalue.In this case it means the class takes one keyword argument (one of
k,f,corr) and if you specify more than one it’ll complain (throw aTypeError) 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.ctranslates tot.__getattr__('c'), andt.c = 23translates tot.__setattr__('c', 23).So, setting one of
t.c,t.fort.rto an integer is routed to the__setattr__method, which then uses theself.coefficientsmapping to calculate and setself.kinstead.Looking up one of
t.c,t.fort.ris routed to the__getattr__method, which then returns a value based on theself.coefficientsmapping together with the existing value ofself.kto give you a temperature in the requested scale.