Skip to content

Commit e8aa372

Browse files
FaiChouyasoob
authored andcommitted
Make sure the function was called (yasoob#154)
* Make sure the function was called Make sure the function was called. * fix class decorator bugs In class decorator, @decorator will call it once, and put the func into Class(func). So if wrote like this `@logit()`, it will call __call__ function. * Update decorators.rst
1 parent b0b6643 commit e8aa372

1 file changed

Lines changed: 20 additions & 8 deletions

File tree

decorators.rst

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -390,18 +390,26 @@ rebuild logit as a class instead of a function.
390390
.. code:: python
391391
392392
class logit(object):
393-
def __init__(self, logfile='out.log'):
394-
self.logfile = logfile
393+
394+
       _logfile = 'out.log'
395+
   
396+
def __init__(self, func):
397+
self.func = func
395398
396-
def __call__(self, func):
397-
log_string = func.__name__ + " was called"
399+
       def __call__(self, *args):
400+
           log_string = self.func.__name__ + " was called"
398401
print(log_string)
399402
# Open the logfile and append
400-
with open(self.logfile, 'a') as opened_file:
403+
           with open(self._logfile, 'a') as opened_file:
401404
# Now we log to the specified logfile
402405
opened_file.write(log_string + '\n')
403406
# Now, send a notification
404407
self.notify()
408+
409+
           # return base func
410+
           return self.func(*args)
411+
412+
           
405413
406414
def notify(self):
407415
# logit only logs, no more
@@ -412,10 +420,14 @@ the nested function approach, and wrapping a function still will use
412420
the same syntax as before:
413421

414422
.. code:: python
415-
416-
@logit()
417-
def myfunc1():
423+
424+
   logit._logfile = 'out2.log' # if change log file
425+
   @logit
426+
   def myfunc1():
418427
pass
428+
429+
myfunc1()
430+
# Output: myfunc1 was called
419431
420432
Now, let's subclass logit to add email functionality (though this topic
421433
will not be covered here).

0 commit comments

Comments
 (0)