我希望熟悉Python編譯/運行時過程的人能夠對我關於Python如何編譯修飾器函數的問題提供一些啓示。Python編譯器函數在編譯時調用
在我的示例代碼中,我已經在定義了logtofile閉包之前在「writeit」裝飾器中包含了一個測試打印語句。如果運行我提供的完整代碼,writeit中的「測試」打印語句將在客戶類中定義的每個@writeit裝飾器調用 - 在使用writeit之前。
爲什麼在編譯時調用logtofile?有人可以解釋這種行爲嗎?
def writeit(func):
print('testing')
def logtofile(customer, *arg, **kwargs):
print('logtofile')
result = func(customer, *arg, **kwargs)
with open('dictlog.txt','w') as myfile:
myfile.write(func.__name__)
return result
return logtofile
class Customer(object):
def __init__(self,firstname,lastname,address,city,state,zipcode):
self._custinfo = dict(firstname=firstname,lastname=lastname,address=address,city=city,state=state,zipcode=zipcode)
@writeit
def setFirstName(self,firstname):
print('setFirstName')
self._custinfo['firstname']=firstname
@writeit
def setLastName(self,lastname):
print('setLastName')
self._custinfo['lastname']=lastname
@writeit
def setAddress(self,address):
print('setAddress')
self._custinfo['address']=address
def main():
cust1 = Customer('Joe','Shmoe','123 Washington','Washington DC','DC','12345')
cust1.setFirstName('Joseph')
cust1.setLastName('Shmoestein')
if(__name__ == '__main__'): main()
它不在編譯時,它在運行時。但是在類定義中運行'def'語句需要運行修飾它們的裝飾器。 – geoffspear