Thanks to visit codestin.com
Credit goes to jugad2.blogspot.com

Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Friday, February 12, 2016

Examples of method chaining in Python


By Vasudev Ram



The topic of method chaining came up during a training program I was conducting. So I thought of writing a post about it, with a couple of examples.

Method chaining is a technique (in object-oriented languages) for making multiple method calls on the same object, without using the object reference more than once. Example:

Let's say we have a class Foo that contains two methods, bar and baz.
We create an instance of the class Foo:
foo = Foo()
Without method chaining, to call both bar and baz in turn, on the object foo, we would do this:
# Fragment 1
foo.bar() # Call method bar() on object foo.
foo.baz() # Call method baz() on object foo.
# With method chaining, we can this:
# Fragment 2
Chain calls to methods bar() and baz() on object foo.
foo.bar().baz()
So you can loosely think of method chaining as the object-oriented version of nested function calls in procedural programming, where, instead of this:
# Fragment 3
temp1 = foo(args)
result = bar(temp)
you would do this:
# Fragment 4
result = bar(foo(args))
We use nested function calls all the time in procedural programming, and even in the procedural sections of code that occur in a Python program that uses OOP. We can do the latter because Python supports both styles (procedural and object-oriented) at the same time, even in the same program; Guido be thanked for that :)

The above was my informal description of method chaining. For more details, refer to this Wikipedia article, which includes examples in various programming languages. The article also makes a distinction between method chaining and method cascading, and according to it, what I call method chaining here (involving returning the self reference) is really method cascading. Are you confused enough? :) Kidding, the difference is not really complex.

One advantage of method chaining is that it reduces the number of times you have to use the name of the object: only once in Fragment 2 above, vs. twice in Fragment 1; and this difference will increase when there are more method calls on the same object. Thereby, it also slightly reduces the amount of code one has to read, understand, test, debug and maintain, overall. Not major benefits, but can be useful.

Note: One limitation of method chaining is that it can only be used on methods which do not need to return any other meaningful value, such as a count of lines modified, words found, records deleted, etc. (which some methods need to do), because you need to return the self object. Even the fact that Python (and some other languages) support returning multiple values from a return statement, may not solve this. (There could be some workaround for this, but it might look awkward, is my guess.)

Simple method chaining can be implemented easily in Python.
Here is one way of doing it:
# foo_bar_baz.py
# Demonstrates method chaining.

class Foo(object):
    def bar(self):
        print "Method Foo.bar called"
        return self

    def baz(self):
        print "Method Foo.baz called"
        return self

foo = Foo()
# Saving return value in foo2 not needed;
# doing to use with id function below.
foo2 = foo.bar().baz()
print

# We can also do it like this, if we don't want 
# to save the object foo for later use:
Foo().bar().baz()
print

# Show that the original foo's id and the returned foo2's id 
# are the same, i.e. they are the same object:
print " id(foo):", id(foo)
print "id(foo2):", id(foo2)
Here is the output of running the above program:
$ python foo_bar_baz.py
Method Foo.bar called
Method Foo.baz called

Method Foo.bar called
Method Foo.baz called

 id(foo): 34478576
id(foo2): 34478576
While writing this post, I also searched for more information, and found a couple of interesting links on method chaining:

Stack Overflow question on method chaining in Python, with some other approaches.

ActiveState Code Python recipe on method chaining

I also wrote another small program, string_processor.py, which shows a somewhat more realistic situation in which one might want to use method chaining:
'''
Program: string_processor.py
Demo of method chaining in Python.
By: Vasudev Ram - 
http://jugad2.blogspot.in/p/about-vasudev-ram.html
Copyright 2016 Vasudev Ram
'''

import copy

class 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()
Does adding the rep() and dup() make it more methodical? :)

Here is the output of running it:
$ python string_processor.py
Demo of method chaining in Python:

Original: 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         fOx
After uppercase: THE      QUICK   BROWN         FOX
After lowercase: the      quick   brown         fox
After uppercase then capitalize: The      quick   brown         fox
After delspace: TheQUIckbrOWnfOx
So, to sum up, we can see that method chaining has its uses, though overdoing it is probably not a good idea.

Finally, and related, via the Stack Overflow article linked above, I came across this post about Collection Pipelines on Martin Fowler's site.

Reading that article made me realize that nested function calls, method chaining and Unix command pipelines are all related concepts. You may also find these other posts by me of interest:

fmap(), "inverse" of Python map() function

Generate PDF from a Python-controlled Unix pipeline

- Enjoy.

- Vasudev Ram - Online Python training and programming

Signup to hear about new products and services I create.

Posts about Python  Posts about xtopdf

My ActiveState recipes


Sunday, March 24, 2013

Video: Minimum Viable Product in Python

By Vasudev Ram

Best tech video I've seen in a long time. Just saw it via a tweet by @raymondh.

Open it in another tab/window:

Video: Class Development toolkit - by Raymond Hettinger

or view it embedded below:



(The embed seems to be truncated; I'll try to tweak the code in a bit.) UPDATE: Fixed the embed.

Raymond Hettinger is a core Python developer and has contributed a lot to many areas of Python. I particularly liked the chapter on generators and iterators in the Python Cookbook, 2nd Edition. He edited and contributed to that chapter, IIRC (I read it a while ago and don't have the book handy right now), and also developed a lot of the stuff on which that chapter is based.

- Vasudev Ram - Dancing Bison Enterprises

Friday, December 7, 2012

Pyreverse creates UML diagrams from Python code

Pyreverse : UML Diagrams for Python (Logilab.org)

Could be useful to reverse engineer and / or document existing code, even for the "executable pseudocode" of a VHLL such as Python, in order to understand it better before making changes to the system.

Pyreverse generates UML diagrams in graphviz / dot / PNG format.

- Vasudev Ram
www.dancingbison.com

Sunday, February 12, 2012

Martin Fowler on GUI architectures


http://martinfowler.com/eaaDev/uiArchs.html

Seen recently. Scanned the article a bit, looks pretty  interesting.

One of the points the article refers to is the principle of separation of (user) interface from implementation, and says that it is a basic concept of MVC (and also of UNIX - see TAOUP *). This is one of my favorite principles of OOP and UNIX, because it is both elegant and facilitates code reuse.

The principle can be applied in both procedural and object-oriented styles of programming. A simple example is that if you design and write your core processing logic in separate functions or classes (i.e. not mix it with the UI code), you can use it from a command-line, desktop GUI, or web application.

* TAOUP is The Art Of UNIX Programming, by Eric Raymond (ESR), who also wrote The Cathedral and the Bazaar. You need a pretty heavy English vocabulary to grok his writings sometimes :), and some people say some of his stuff is a lot of guff, but I think he has a lot of good points.

--- Vasudev Ram
www.dancingbison.com

Monday, October 10, 2011

Matchmaker can ease object-oriented program maintenance

By Vasudev Ram - dancingbison.com | @vasudevram | jugad2.blogspot.com

Matchmaker looks interesting and may help in some cases to ease and speed up maintenance / enhancement of object-oriented programs, particularly open-source ones.

Article about Matchmaker:

http://www.physorg.com/news/2011-10-oracle-object-oriented-programmers.html

(The above article was republished on the PhysOrg site courtesy of MIT News (http://web.mit.edu/newsoffice/)

Excerpts:

[ Matchmaker is a research system that "automatically determines how objects in a large software project interact, so it can inform latecomers which objects they will need to design certain types of functions. The system could be of particular use to programmers working with open-source software, whose licensing terms require that its underlying code be publicly disclosed. Someone wishing to simply add a function to a common open-source program, for instance, may not want to spend the week it takes to get up to speed on all the program's objects.
...
Matchmaker builds up its database of object linkages in a program's source code by monitoring the program's execution. In the case of Eclipse, it noticed that every time a Scanner was invoked, so were the other objects.
...
Foster points out that Matchmaker can't answer all the questions that a programmer new to an application might have.
...
Still, Foster says, in the instances where Matchmaker is applicable, "you're going to get result that's vastly superior. You're going to get a result in seconds or minutes instead of having to search on Google, filter out a lot of bad answers, figure out what people meant when they explained various things — if the tool works for the problem, it's very useful." ]

Posted via email

- Vasudev Ram @ Dancing Bison