2011-10-25 175 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最後。