Python class dynamic modification instance method, python class dynamic instance

Source: Internet
Author: User

Python class dynamic modification instance method, python class dynamic instance

Dynamic Modification of Python class instance method

I believe many of my friends will want to modify the code of program behavior when programming. The most common method is to rewrite some methods of the parent class that do not meet the requirements through subclass. For example, the following example is used.

class Dog:  def bark(self):    print 'Woof!' class Husky(Dog):  def bark(self)    print 'Howl!'

We can use the above method to modify our own code, But how should we modify the third-party code? Of course, we can also compile a subclass by ourselves and call the Instance Object of the subclass for modification, but this may introduce a series of other problems. Therefore, we have to find a way to replace the original object method with our own method. This is the "Patching" method to be introduced next in this article.

Patch categories

If we want to add or modify the object method, the simplest way is to patch the class. Based on the above example, if we want to write a new howl Method for our Dog class, we can define a new howl function, add it to our class like the following code:

def newbark(self):  print 'Wrooof!' def howl(self):  print 'Howl!' # Replace an existing methodDog.bark = newbark # Add a new methodDog.howl = howl

Is it easy? However, there are several issues that need attention. First, the methods in all instances of the modified class will be updated. Therefore, the updated method not only exists in the newly created object, but also has the updated method for all previously created objects, unless you only add a new method instead of overwriting the original method. Second, the method you modify or add should be bound to the object, so the first parameter of the method should be the called object (here is the instance self of the class ).

Patch a class instance

A single object can be patched without affecting other instances of this class. But it's a little tricky! Let's take a look at the example below.

def herd(self, sheep):  self.run()  self.bark()  self.run() border_collie = Dog()border_collie.herd = herd

Then we try to call the new definition method:

border_collie.herd(sheep) TypeError: herd() takes exactly 2 arguments (1 given)The problem with the previous code is that the herd is not a bound method, just take a look at the following code: print border_collie.herd <function herd at 0xf9c5f0>

An error occurred! The cause of the error is that the called object is not passed to the function we wrote as the first parameter. Of course, we can pass in the parameters by ourselves, but it does not work in this replacement class method scenario. The correct solution to this problem is to use the MethodType function in the type module. Let's look at the following sample code:

import types border_collie = Dog()border_collie.herd = types.MethodType(herd, border_collie) print border_collie.herd<bound method ?.herd of <__main__.Dog instance at 0x23c9518>> border_collie.herd(sheep)

Now our method has been bound to the instance. This is a success!

Summary

It is very useful to replace or add methods during running. For example, in unit testing, some functions responsible for communicating with external services need to be replaced to facilitate testing. This technique is not only very common, but also maintains the maintainability of the code before you decide to modify the code. It is a very important technique.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.