簡體   English   中英

Python Assign-Print語句?

[英]Python Assign-Print statement?

因此,我正在編寫一些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)

如果我將其輸入到交互式外殼中,它將自動向我吐出中間組件的值:

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

很好,因為賦值語句被保留,這意味着我確切知道下一個值是什么。 但是,將其放在交互式外殼中的問題是進行更改並重新運行整個腳本(這需要數十次計算)很繁瑣。 在通過python script.py運行的腳本中,有什么方法可以實現此功能?

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

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

不要忘記適當地設置記錄器

Ignacio功能的改進版本:

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")

考慮使用pdb監視執行。 我懷疑您在計算完后會想要所有這些日志記錄語句。

Doug Hellmann有一個很好的使用pdb的示例

我認為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...並取消縮進類主體即可。 這樣做的主要限制是您不能從類主體內部return ,因此,如果需要返回值,則必須為其命名,例如最后return ShowMe.LengthOfWire

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM