How to use the method chain in Python, and how to use python

Source: Internet
Author: User

How to use the method chain in Python, and how to use python

Method chaining)It is a common syntax in object-oriented programming languages. It allows developers to call the same object multiple times when only one object is referenced. For example:

Suppose we have a Foo class, which contains two methods: bar and baz.

Create an instance of the Foo class:

foo = Foo()

If you do not use a method chain and want to continuously call the bar and baz methods of the object foo, we have to do this:

foo.bar() # Call method bar() on object foo.foo.baz() # Call method baz() on object foo.

If the method chain is used, we can implement: foo. bar (). baz ()

One advantage of method chain is that you can reduce the number of times you use the object name. The more methods you call, the more times you can reduce them. Therefore, this method can reduce the number of codes that need to be read, tested, debugged, and maintained to a certain extent. This is not good, but it is also useful.

Note that one restriction of method chain is that it can only be used in methods that do not need to return other values, because you need to return the self object. This problem may not be solved even if Python supports returning multiple values with a return statement.

The following is an example of method chain implementation in Python:

class Person:  def name(self, value):    self.name = value    return self  def age(self, value):    self.age = value    return self  def introduce(self):    print "Hello, my name is", self.name, "and I am", self.age, "years old."person = Person()person.name("EarlGrey").age(21).introduce()# => Hello, my name is EarlGrey and I am 21 years old.

The above implementation may be too simple. Next let's look at a more realistic method chain usage method: compile a string processing program string_processor.py, supporting method chain.

import copyclass StringProcessor(object):  '''  A class to process strings in various ways.  '''  def __init__(self, st):    '''Pass a string for st'''    self._st = st  def lowercase(self):    '''Make lowercase'''    self._st = self._st.lower()    return self  def uppercase(self):    '''Make uppercase'''    self._st = self._st.upper()    return self  def capitalize(self):    '''Make first char capital (if letter); make other letters lower'''    self._st = self._st.capitalize()    return self  def delspace(self):    '''Delete spaces'''    self._st = self._st.replace(' ', '')    return self  def rep(self):    '''Like Python's repr'''    return self._st  def dup(self):    '''Duplicate the object'''    return copy.deepcopy(self)def process_string(s):  print  sp = StringProcessor(s)  print 'Original:', sp.rep()  print 'After uppercase:', sp.dup().uppercase().rep()  print 'After lowercase:', sp.dup().lowercase().rep()  print 'After uppercase then capitalize:', sp.dup().uppercase().\  capitalize().rep()  print 'After delspace:', sp.dup().delspace().rep()def main():  print "Demo of method chaining in Python:"  # Use extra spaces between words to show effect of delspace.  process_string('hOWz It   GoInG?')  process_string('The   QUIck  brOWn     fOx')main()

The running result of this program is as follows:

$ python string_processor.pyOriginal: hOWz It   GoInG?After uppercase: HOWZ IT   GOING?After lowercase: howz it   going?After uppercase then capitalize: Howz it   going?After delspace: hOWzItGoInG?Original: The   QUIck  brOWn     fOxAfter uppercase: THE   QUICK  BROWN     FOXAfter lowercase: the   quick  brown     foxAfter uppercase then capitalize: The   quick  brown     foxAfter delspace: TheQUIckbrOWnfOx

In summary, we can find that the method chain has its own advantages, but it may not be good to use it too much.

How to Use method chains in Python? I believe that everyone has a general idea. I hope this article will help you learn it.

Articles you may be interested in:
  • Methods can also be used in PHP.
  • A simple example of implementing chained operations (method chains) in JAVA
  • Method Chaining in Javascript

Related Article

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.