0

我正在阅读 Python Cookbook,他们在那里有这个程序:

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

我不明白以下内容 - 有人可以帮我这样做吗?:

  1. 这个功能是做什么的name, value = kwargs.popitem( )
  2. 做什么__getattr____setattr__做什么。他没有在程序的最终调用中使用这些

这是输出:

>>> 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
4

1 回答 1

4
  • kwargs.popitem()方法从字典中删除一个(任意)项目kwargs并将其作为(key, value)元组返回。然后将其分配给两个变量namevalue

    在这种情况下,这意味着该类采用一个关键字参数(之一k,,或) f,如果您指定多个,它会在查看您传入的关键字参数之一后抱怨(抛出一个) 。crTypeError

  • __getattr__并且是 python 在查找属性__setattr__时使用的特殊方法。

    t.c转换为t.__getattr__('c'),并t.c = 23转换为t.__setattr__('c', 23)

    因此,将 或 设置t.ct.f一个t.r整数将被路由到该__setattr__方法,然后该方法使用self.coefficients映射来计算和设置self.k

    查找或之一被路由到该方法t.c,然后该方法根据映射返回一个值以及 的现有值,从而为您提供所需比例的温度。t.ft.r__getattr__self.coefficientsself.k

于 2013-01-16T08:46:44.540 回答