
Python has a magic function __getattr__ that can be automatically executed when an attribute of an object is called. Using this, we can implement very flexible functions.
For example, to calculate the addition, subtraction, multiplication and division of two numbers, you only need to pass in one parameter to perform the calculation:
File: The content of dynamic_attr_of_class.py is as follows:
class DynamicAttr(object):
def __getattr__(self, name):
op, num = name.split("_")
num = int(num)
return {
"times": lambda val: val * num,
"plus": lambda val: val + num,
"minus": lambda val: val - num,
"dividedby": lambda val: val / num,
}[op]
if __name__ == "__main__":
da = DynamicAttr()
assert da.plus_10(13) == 23
assert da.times_10(13) == 130
assert da.minus_10(13) == 3
assert da.dividedby_10(13) == 1.3
The above code, when calling da.plus_10 , will call __getattr__ . After executing op, num = name.split("_") , op = 'plus', num = 10.
The final return is a lambda function, the parameter is val, so da.plus_10 is equivalent to lambda val: val + 10, so da.plus_10(13) is 13 + 10 = 23.
As of Python 3.7, __getattr__ can provide dynamic attributes not only for classes, but also for modules.
The above __getattr__ function can be directly defined in a module (a Python file), for example, the content of the file dynamic_attr_of_module.py is as follows:
def __getattr__(name):
op, num = name.split("_")
num = int(num)
return {
"times": lambda val: val * num,
"plus": lambda val: val + num,
"minus": lambda val: val - num,
"dividedby": lambda val: val / num,
}[op]
In another file, main.py, it can be used like this:
import dynamic_attr_of_module as da
if __name__ == "__main__":
assert da.plus_10(13) == 23
assert da.times_10(13) == 130
assert da.minus_10(13) == 3
assert da.dividedby_10(13) == 1.3
Is it convenient and flexible?
last words
This article shares how to use Python's dynamic properties to implement some cool functions: reduce function parameters, for example. You can also think about what magical things this __getattr__ can achieve. Welcome to leave a message to share.
- For cooperation, communication and reprint, please add WeChat moonhmily1 -