Monkey patch (monkey patch) is the main function of the properties and methods of dynamic replacement (really super unchaste)
Since Python is an object-oriented programming, so all the class, instance objects, packages can be imported as an object.
Prime Minister definition of a simple class:
class A(): pass
Examples of a = A ()
Well, this class A property with no default method inside
There are also no examples of a method of Example
First, we can be the hands and feet of class A, class A which can add object methods, class static methods, class properties, (class method did not discover how to temporarily add)
Externally defined a few simple functions:
def c_func_add(x, y): return x + y def cs_func_multiply(self, x, y): return x * y def s_func_show(): print('i am add func')
In [103]: A.c_f = c_func_add In [104]: A.cs_f = cs_func_multiply In [106]: a = A() In [107]: a.s_f = s_func_show In [108]: A.c_f(1,2) Out[108]: 3 In [109]: a.cs_f(2,3) Out[109]: 6 In [110]: a.s_f() i am add func
The entire process is performed in the definition of the class in the instance object and, which may be added in different ways, in fact, this experiment did not, is also possible to add attributes, A.name = 'lala' or a.name = 'haha', when the input belongs to a class attribute, respectively, an instance attribute.
Monkey pudding Another advantage is that you are in a different import modules such as module1, module2.
You might use module2 inside into the method, you can directly through module1.into = moddule2.into
If the method module1 which already has defined the back cover.
Today met a more interesting case study in Django, when used get_or_greate method, in order to reduce the interaction with the database query, you can monkey pudding way to cache query results first instance properties inside.
This can greatly reduce the actual process of interaction in the database.
if not hasattr(self, '_profile'): self._profile, _ = Profile.objects.get_or_create(id=self.id) return self._profile
Master teacher learned a lot, signs, so as not to forget the future