Python Decorator

Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

1. define function

def ucapan(nama):
    return "Halo " + nama 

functions are first class objects in python, this is simply the observation that in Python, functions are objects like everything else.

>>> type(ucapan)
<class 'function'>
>>> issubclass(type(ucapan), object)

2. calling it

>>> ucapan('opik')
'Halo opik'

3. assign function to other variable

 >>> ucap_ke_seseorang = ucapan
>>> ucap_ke_seseorang
<function ucapan at 0x01FBACD8>

4. call this new function

>>> ucap_ke_seseorang('opik')
'Halo opik'

5. Functions can be passed as parameters to other functions, so lets defines it, for ex:

>>> def panggil(fungsi):
        nama_lain = "black widow"
        return fungsi(nama_lain)
>>> panggil(ucapan)
'Halo black widow'

6. nested functions (functions defined inside other functions)

>>> def ucapanku(nama):
        def pesan():
            return "Selamat datang "
        hasil = pesan() + nama
        return hasil
>>> ucapanku('black mamboo')
'Selamat datang black mamboo'

7. Functions can return other functions

>>> def buat_ucapan():
        def pesan():
            return "Halo "
        return pesan

>>> selamat = buat_ucapan()
>>> selamat()
'Halo '

8. Closure
Inner functions have access to the enclosing scope commonly known as a closure

9. Decorators

>>> def ucapan(nama):
        return "Selamat datang {}".format(nama)

>>> ucapan('paijo')
'Selamat datang paijo'
>>> def buat_ucapan(fungsi):
        def ucapan_selamat(nama):
            return "Welcome my friend, {}".format(fungsi(nama))
        return ucapan_selamat

10. decorator syntax

>>> ucapanku = buat_ucapan(ucapan)
>>> ucapanku('black mamboo')
'Welcome my friend, Selamat datang black mamboo'
>>> ucapan
<function ucapan at 0x01D4ACD8>
>>> ucapanku
<function buat_ucapan.<locals>.ucapan_selamat at 0x01D4F660>
>>> ucapan = buat_ucapan(ucapan)
>>> ucapan('black widow')
'Welcome my friend, Selamat datang black widow'

11. Decorator with syntatic sugar

>>> @buat_ucapan
    def ucapan(nama):
        return "Selamat datang " + nama

>>> ucapan('black something')
'Welcome my friend, Selamat datang black something'

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: