Created
February 19, 2021 05:31
-
-
Save ceshine/318476922b8ed42aa7aaa7e0fac70c98 to your computer and use it in GitHub Desktop.
Demo of the @patch_to decorator from fastcore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastcore.basics import patch_to | |
class Demo: | |
val = 10 | |
def __init__(self, val): | |
self.val = val | |
# ==================== | |
# The default mode | |
# ==================== | |
@patch_to(Demo) | |
def print(self): | |
print(self.val) | |
Demo(5).print() # prints 5 | |
# ======================= | |
# The class method mode | |
# ======================= | |
@patch_to(Demo, cls_method=True) | |
def print(self): | |
print(self.val) | |
Demo(5).print() # prints 10 | |
# ===================== | |
# The property mode | |
# ===================== | |
@patch_to(Demo, as_prop=True) | |
def print(self): | |
print(self.val) | |
Demo(5).print # prints 5 | |
# ===================== | |
# Addition notes | |
# ===================== | |
# | |
# The function under @patch_to doesn't overwrite existing functions. | |
# In this example, the global `print` built-in function still works normally: | |
print("I am a print statement.") # prints I am a print statement. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment