Method decorators in Python

By : Akshar Raaj

This post assumes you have a basic understanding of Decorators. If not, you can read our introductory post on Decorator

Method decorators

In introductory post, we learnt about function decorators. In this post we'll see method decorators:

Let's write a Class and a method on it which we will decorate later.

>>> class Person(object):
...     def __init__(self, name):
...         self.name = name
...     def print_name(self):
...         print self.name

Create a Person instance. p1 refers to the created instance.

>>> p1 = Person("eddard")

Call print_name on Person.

>>> p1.print_name()
eddard     #output

Something worth noting about previous Python statement. Quoting from docs

"The method function is declared with an explicit first argument representing the object, which is provided implicitly by the call"

It means, call p1.print_name() implicitly passes p1 to method print_name. And so self in print_name starts referring to our created Person instance.

There is another way in which print_name() can be called on p1. Knowing this way would make understanding method decorator easier.

>>> Person.print_name(p1)
eddard     #output

In last statement, print_name() wasn't called on p1, but instead called on class Person. So p1 couldn't be passed to print_name() implicitly. It had to be done explicitly.

This paragraph is important. We can think a method as just a function. If provided with correct arguments, it would work similar to any other function. If called on the instance, instance is passed implicitly as the argument and so method/function works. If called on class, instance has to be passed explicitly and then method/function works. So, most of the things which can be done with a function can be done with the method. Let's play around with it a little.

>>> some_func = Person.print_name
>>> some_func(p1)
eddard     #output

>>> Person.another_print_name_reference = Person.print_name
>>> Person.another_print_name_reference(p1)
eddard     #output

Scenario for using decorator

We want Person.print_name code to be executed only if name of the Person instance is not "joffrey". Let's write the decorator for it.

>>> def decorate_method(method):
...     def inner(person_instance):
...         if person_instance.name == "joffrey":
...             print "What a stupid name, I won't print name for you"
...         else:
...             method(person_instance)
...     return inner
Structure of decorate_method
  • Signature of function created by the decorator, which in our case is function named inner, should be similar to signature of the function it is trying to decorate.
  • Here we are trying to decorate a method, print_name, which ultimately is a function. And this function expects a Person instance as its only argument.
  • So inner is defined to expect one argument too.

Let's use this decorator without using decorator syntax.

>>> Person.decorated_print_name = decorate_method(Person.print_name)
>>> p1.decorated_print_name()
eddard     #output

>>> p2 = Person("joffrey")
>>> p2.decorated_print_name()
What a stupid name, I won't print name for you

Let's use this decorator with decorator syntax.

>>> class Person(object):
...     def __init__(self, name):
...         self.name = name
...     @decorate_method
...     def print_name(self):
...         print self.name

So, this was similar to saying:

Person.print_name = decorate_method(Person.print_name)

Using our decorated method:

>>> p1 = Person("eddard")
>>> p1.print_name()
eddard
>>> p2 = Person("joffrey")
>>> p2.print_name()
What a stupid name, I won't print name for you


Related Posts


Can we help you build amazing apps? Contact us today.

Topics : python Decorators

Comments

Sukumaran 1st Aug., 2014

Hi Akshar Raaj

I started reading your python stuffs and it looks to be very very good. I did some of the small small application using python and python tkinter, but I didn't try to use any of the design pattern. When I started to learn singleton, I came across your blog and feels that it is very very nice and very good one to understand internal concepts.

Thanks for your post and expects more from you
Please let me know if you want any help. May be I can help you
Regards
Sukumaran

commmenttor
Size 60 jerseys shop

ONLY ON 7 TONIGHT. KOAT ACTION 7 NEWS REPORTER ANNA VELASQUEZ EXPLAINS HOW THE BLASTS HAVE IMPACTED THE NORTHEAST HEIGHTS, FOR MONTHS. IN MID MARCH, ACTION 7 NEWS FOUND INVESTIGATORS AT VILLELA PARK, LOOKING FOR CLUES AFTER A BLAST RIPPED A TRASH CAN TO SHREDS. THE EXPLOSION RATTLED NERVES. It was a loud bang, just a very loud bang kind of shook everything in the house. AND NOW, THE FBI WANTS TO KNOW WHO PLANTED THAT BOMB, AND FOUR OTHERS AROUND THE NORTHEAST HEIGHTS DURING A SIX MONTH PERIOD. people may think this is a prank. But it is very serious. And it could lead to serious federal consequences ON OCTOBER 2ND, A BOMB WENT OFF IN A PARKING LOT ON WISCONSIN NEAR WYOMING AND MENAUL. THEN ANOTHER ON JANUARY 6TH, BEHIND A BUINSESS ON WYOMING NEAR CANDELARIA. THERE WAS A THIRD EXPLOSION ON VALENTINE'S DAY AT HOFFMAN PARK, NORTHEAST OF WYOMING AND MENAUL. BUT IT'S WHAT INVESTIGATORS FOUND AT KIVA PARK, THAT COULD HELP PROVIDE CRUCIAL CLUES. we want people to take a good look at these sunglasses and contact us if they may know who the owner of these sunglasses was AND HERE AT VILLELA PARK, THE FBI SAYS NEIGHBORS SPOTTED A SILVER, TWO DOOR CAR WITH A SPOILER AND A TURQUOISE NEW MEXICO PLATE. no tip is too small. You could have the answer to this case we're looking for THIS IS THE FLYER THE FBI SENT HOME WITH LOCAL HIGH SCHOOL STUDENTS TODAY. WE'RE TOLD THEY'LL DISTRIBUTE IT NATIONWIDE, TOMORROW. THE FBI HAS NO NEW REPORTS OF SIMILAR EXPLOSIONS SINCE MID MARCH. NO ONE WAS HURT DURING ANY OF THE FIVE

commmenttor
wholesale cheap mac makeup 050155

nike free run white and pink 321342 nike free herre udsalg 450534 urban decay make up 011500 Hogan Catalogo Ufficiale 410013 Scarpe Hogan Donna 2014 101545 Hogan Da Uomo 025523
wholesale cheap mac makeup 050155 http://www.mafrat.com/public/cheapmacmakeupwholesale/wholesale_cheap_mac_makeup_050155.asp

commmenttor
seahawks jerseys cheap

Months of planning and experimenting has paid off for Tachibana as the Antique's business is booming. He now has two fine pastry chefs under his roof and enough trained staff to keep the place running practically whenever he wanted. For a shrewd businessman like Tachibana this is an accomplishment that was expected. However, Tachibana reasoning could not have been foreseen by anyone who was not a true regular of the Antique.

commmenttor
ceinture louis vuitton pas cher

La jalousie des bêtises une classe est ah si noir, fait parjure, condamné à un tel avocat est nécessaire. Une telle lecture du rapport officiel sur la valeur nominale.

commmenttor
best hermes replica

best hermes replica fake revealed hermes nyc pjsfxv

commmenttor
nike free run

The Coast Guard say the Seattle based Cape Cross had a capacity of 3,000 gallons, but was not full when it tipped on its side in Main Bay on Monday. Crews have removed 1,200 gallons of fuel from the 100 foot vessel. Beck was ashore when he saw the canoe flip over, losing sight of the two hunters.

commmenttor
imitation ray ban 2014 nissan juke

Currently there is no data to suggest that this compound is toxic. Although there are three cases in Germany in which the patients were diagnosed with hepatitis and I believe that this is referring to kidney failure and not the virally transmitted disease. Two of the patients recovered after they quit taking the compound but one patient had to under go a kidney transplant.

commmenttor
nike free run uk sale

Most of the people imitate styles of few celebrities from bollywood to have a ravishing look and attractive personality. Bollywood stars like Sonam Kapoor who is a Brand Ambassador of French beauty brand Loreal Paris. She is one of the refined bollywood diva which possess phenomenal style and best appearance in the festivals like CANNES. She deserves to be known as youth fashion Icon. When we look at her sunglasses style, we find an awesome shape style that matches her face accordingly her wardrobes.

commmenttor
Post a comment Name :

Email :

Your site url:

Comment :

© Agiliq, 2009-2012