我希望熟悉 Python 的编译/运行时过程的人可以对我关于 Python 如何编译装饰器函数的问题有所了解。
在我的示例代码中,在定义 logtofile 闭包之前,我在“writeit”装饰器中包含了一个测试打印语句。如果您运行我提供的整个代码,那么在使用 writeit 之前,会为 Customer 类中定义的每个 @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()