2011-10-25 120 views
2

所以我写一些Python脚本来帮助我做一些简单的计算:Python分配 - 打印语句?

WireRadius = .455/1000/2 #m, 25AWG 
CoilInnerRadius = 10.0/1000/2 #m 
CoilOuterRadius = 20.0/1000/2 #m 
CoilLength = 20.0/1000 #m 
CoilVolume = 3.14 * (CoilOuterRadius**2 - CoilInnerRadius**2) * CoilLength #m^3 
print "CoilVolume: " + str(CoilVolume) 
WireCrossSection = 3.14 * WireRadius**2 #m^2 
print "WireCrossSection: " + str(WireCrossSection) 
LengthOfWire = CoilVolume/WireCrossSection/2 #m 
print "LengthOfWire: " + str(LengthOfWire) 

现在,我希望脚本打印出所有的中间部件,这样我就可以看到是怎么回事。如果我搞砸了,这也让我找准线在我的数学是错误的,因为这时候的数字变得无意义。

但是,这显然不是很干,因为我写了每个变量名不是一次,两次,而是三次:

LengthOfWire = CoilVolume/WireCrossSection/2 #m 
print "LengthOfWire: " + str(LengthOfWire) 

如果我打字到这个交互shell,它会自动吐出中间部件的值回我:

>>> LengthOfWire = CoilVolume/WireCrossSection/2 #m 
14.491003502 

这是相当不错的,因为赋值语句被保留的意思我知道下一个值是什么。然而,把它在交互shell的问题是,更改并重新运行整个脚本(这是几十个计算长)是乏味的。有没有什么办法可以在通过python script.py运行的脚本中实现这个功能?

回答

3
def debug(val): 
    logging.debug('DEBUG: %r', val) 
    return val 

... 
LengthOfWire = debug(CoilVolume/WireCrossSection/2) 

不要忘记适当地设置您的logger

2

伊格纳西奥的功能的改进版本:

import logging 

def debug(val, label=None): 
    """Prints a debug message consisting of a value and an optional label.""" 
    if label is None: 
    logging.debug('DEBUG: %r', val) 
    else: 
    logging.debug('DEBUG: %s = %r', label, val) 
    return val 

... 
LengthOfWire = debug(CoilVolume/WireCrossSection/2, label="Wire length") 
0

我觉得debug功能可能是最好的,但如果你真的想要做的任务,而不模糊的表达,它实际上是可以使用元类:

class print_dict(dict): 
    def __setitem__(self, key, value): 
     if not key.startswith('_'): 
      print("{}: {}".format(key, value)) 
     super().__setitem__(key, value) 


class MetaPrint(type): 
    @classmethod 
    def __prepare__(metacls, name, bases): 
     return print_dict() 
    def __new__(cls, name, bases, classdict): 
     result = type.__new__(cls, name, bases, dict(classdict)) 
     return result 


def foo(x): 
    class ShowMe(metaclass=MetaPrint): 
     WireRadius = x/1000/2 #m, 25AWG 
     CoilInnerRadius = 10.0/1000/2 #m 
     CoilOuterRadius = 20.0/1000/2 #m 
     CoilLength = 20.0/1000 #m 
     CoilVolume = 3.14 * (CoilOuterRadius**2 - CoilInnerRadius**2) * CoilLength #m^3 
     WireCrossSection = 3.14 * WireRadius**2 #m^2 
     LengthOfWire = CoilVolume/WireCrossSection/2 #m 

foo(.455) 

然后,当你把一切都整理只是删除class ShowMe...行和unindent类的主体。这个主要的限制是,你可以从类体内不return,所以如果你需要一个返回值,你必须给它一个名称,例如return ShowMe.LengthOfWire最后。