peri hokiperihokiclarustologisticsrimashaop.compola taktis menang gates of olympus x1000 perihokipemain perihoki bongkar trik jepep starlight princess x1000perihoki beri panduan lengkap bermain mahjong ways 2 pgsofttips cara penghasil uang pgsoft mahjong ways 2 perihokimahjong wins 3 perihoki memberikan penggali terbesarfenomena gates of olympus buka peluang besar bagi duta76cara dapat pola emas rahasia di duta7 wild west goldtrik menang pgsoft mahjong ways 2 modal receh maxwin duta76duta76 main pgsoft mahjong ways 2 di sela istirahatscatter hitam mahjong wins 3 spin pasti jepe duta76perihoki spin mahjong ways 2 pgsoft scatter hitam maxwinsimbol mahjong wins 3 yang sering muncul di awal perihokitrik gampang menang mahjong winscuan mahjong wins 3 tanpa hentipola spin taruhan kecil mahjong winsstrategi kunci scatter hitam beruntungacor total mahjong wayskemenangan maksimal mahjong wayskemenangan pria pekanbaru mahjong waysmahjong wins3 fenomena baru sumatera baratmenangkan mahjong dengan lincahmenembus batas keberuntungan mahjong waysmenjajal keberuntungan di mahjong wayspola gratis mahjong ways1scatter hitam senjata rahasia mahjong winsteknik spinning menguntungkan untuk scatter hitamanalisis rtp tertinggi mahjong winsfenomena scatter hitam mahjong winsibu rumah tangga dan keberuntungan mahjongkeseruan main mahjong wins3menang mahjong pengguna baru di sosial mediamenghargai setiap momen di mahjong waysserunya main mahjong di warung internetspin slow motion mancing scatterstrategi jitu maxwin mahjong waysstrategi jitu menang mahjong modal kecil jackpot besaranak kampung papua menggemparkan mahjongkeajaiban scatter hitam mahjong wayskeberhasilan joni mahjong winskejaiban mahjong ways di ujung jalanketua mahjong wins3 kehadiran kemenangan dimulai dari balimahjong kehadiran yang menguntungkanmahjong menggila adat88panduan kilat raih 108 jutatips memenangkan mahjongbarista kopi menang 110 juta spin mahjongdakota76 scatter hitam mahjong wins 3gagal cpns menang mahjong wins 3 rp120 jutakisah karyawan minimarket dapat thr lebih awal mahjong winskisah pelajar sma kuasai mahjong wins 3 inspirasi sekolahkisah penjaga parkir tanah abang motor baru mahjong winskisah sukses ibu rumah tangga bandung mahjong winsmahasiswa kkn beli iphone15 mahjong wins3 dakotamantan anak band influencer mahjong scatter hitampola rtp senin gates of olympus guru matematikatukang cuci motor menemukan keberuntungan di mahjong

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Cannot change session cookie parameters when headers already sent

Filename: Session/Session.php

Line Number: 294

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 304

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 314

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 315

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 316

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 317

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 375

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Cannot change save handler when headers already sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Cannot start session when headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

Decorator trong Python - Freetuts
INTRODUCTION
FLOW CONTROL
FUNCTIONS
DATATYPES
OBJECT & CLASS
Bài tập Python: Lập trình hướng đối tượng (OOP) trong Python Lập trình hướng đối tượng trong Python Class Variables trong Python Tìm hiểu về Methods trong Python Cách sử dụng phương thức __init__() trong Python Các biến Instance trong Python Tìm hiểu về Class Attributes trong Python Hàm Static Methods trong Python Phương thức __str__ trong Python Phương thức __repr__ trong Python Phương thức eq trong Python Tìm hiểu phương thức __hash__ trong Python Phương thức __bool__ trong Python Phương thức del trong Python Tìm hiểu về lớp Property trong Python Tìm hiểu về nạp chồng toán tử trong Python Trình Decorator Property trong Python Thuộc tính chỉ đọc trong Python Thuộc tính Delete trong Python Sử dụng super() trong Python Sử dụng __slots__ trong Python Cách sử dụng Protocol trong Python Sử dụng Enum aliases và @enum.unique trong Python Tùy chỉnh và mở rộng lớp Enum trong Python Cách sử dụng hàm Auto() của Python Single Responsibility Principle trong Python Nguyên tắc Đóng-Mở trong Python Nguyên tắc thay thế Liskov - LSP trong Python Interface Segregation Principle - ISP trong Python. Nguyên tắc đảo ngược sự phụ thuộc trong Python Đa kế thừa trong Python Tìm hiểu về các lớp mixin trong Python Mô tả Descriptors trong Python Phân biệt Data Descriptor và Non-data Descriptor trong Python Phương thức __new__ trong Python Tìm hiểu về Class Type trong Python Lớp Metaclass trong Python Ví dụ sử dụng metaclass trong Python Tìm hiểu về decorator dataclass trong Python Tìm hiểu về các ngoại lệ trong Python Ngoại lệ Raise trong Python Sử dụng câu lệnh raise from trong Python Ngoại lệ tùy chỉnh trong Python Module trong Python Package trong Python Class trong Python Hàm khởi tạo trong Python Kế thừa trong Python Đa kế thừa trong Python Setter và Getter trong Python Override trong Python Interface trong Python Bài tập Python: Module và Class
ADVANCED TOPICS
BỔ SUNG
PYTHON CĂN BẢN
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

Thông báo: Download 4 khóa học Python từ cơ bản đến nâng cao tại đây.

Decorator trong Python

Trong bài này chúng ta sẽ tìm hiểu cách dùng Decorator trong Python, dựa vào cấu trúc của nested function ta có thể tạo ra những decorator một cách dễ dàng.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Các hàm trong Python là first-class (lớp đầu tiên), điều này có nghĩa là các hàm sẽ có trạng thái bình đẳng với những đối tượng object khác trong Python. Điều này có nghĩa là các hàm có thể được gán cho biến, được truyền vào như một tham số, được lưu trữ trong các collection.

1. Python decorator là gì?

Python decorator là cách thay đổi hành vi (behavior) của một object callable mà không cần can thiệp và chỉnh sửa object đó. Decorator là một hàm có nhiệm vụ bao bọc một hàm khác (ta tạm gọi là hàm B), hàm B sẽ được gọi bên trong thân của hàm decorator, và đương nhiên lúc này hàm decorator có thể bổ sung những đoạn code phía trên và phía dưới vị trí gọi hàm B.

Hãy lấy một ví dụ cho dễ hiểu: Giả sử bạn viết một hàm in ra các số từ 1 đến 10 như sau:

Bài viết này được đăng tại [free tuts .net]

def showNumbers():
    for i in range( 1, 11):
        print(i, end=' ')

showNumbers()

Nhưng hôm sau bạn muốn in thêm một dòng dấu sao ở phía trên và phía dưới của các số đó nữa thì làm thế nào? Cách đơn giản nhất là sửa lại hàm đó.

def showNumbers():
    print('*********************************')
    for i in range( 1, 11):
        print(i, end=' ')
    print('')
    print('*********************************')

showNumbers()

Nhưng cách làm này sẽ không hiệu quả nếu function showNumbers mình đã sử dụng ở rất nhiều nơi, nếu sửa trực tiếp như vậy sẽ làm ảnh hưởng đến những vị trí đó.

Để giải quyết thì mình sẽ kết hợp với higher order function để tạo ra decorator.

# Đây là hàm decorator
def decoratorFunc(func):
    # Đây là hàm decorator gọi,
    # ta gọi là extend decorated function
    def addStar():
        print("***************************")
        func()
        print('')
        print("***************************")

    return addStar

def showNumbers():
    for i in range( 1, 11):
        print(i, end=' ')


add_star = decoratorFunc(showNumbers)
add_star()

Trong ví dụ này thì hàm decoratorFunc là một decorator, bên trong được gọi đến hàm mở rộng addStar dùng để trang trí thêm mấu dấu sao.

2 Tạo decorator trong Pyhton bằng dấu @

Python cho phép bạn sử dụng dấu @ để đánh dấu một phương thức sẽ được trang trí (decorator) bằng một phương thức khác.

Quay lại ví dụ trên thì mình sẽ viết lại chương trình decorator như sau:

def decoratorFunc(func):
    def addStar():
        print("***************************")
        func()
        print('')
        print("***************************")

    return addStar

@decoratorFunc
def showNumbers():
    for i in range( 1, 11):
        print(i, end=' ')

# Gọi kiểu này đơn giản hơn
showNumbers()

Kết quả trả về là như nhau:

decorator in python JPG

Kể từ bây giờ chúng ta nên sử dụng cách này nhé các bạn, bởi trông chuyên nghiệp và ảo diệu hơn rất nhiều, một người không rành về Python sẽ không thể hiểu là bạn đang code cái gì :3

3. Python decorator với hàm có tham số

Trường hợp hàm showNumbers có tham số thì cách viết như thế nào nhỉ?

Giả sử mình fix lại hàm đó với một tham số n truyền vào, và nội dung sẽ in ra dãy số từ 1 đến n.

def decoratorFunc(func):
    def addStar(n):
        print("***************************")
        func(n)
        print('')
        print("***************************")

    return addStar

@decoratorFunc
def showNumbers(n):
    for i in range( 1, n + 1):
        print(i, end=' ')

# Gọi có tham số truyền vào
showNumbers(20)

Các bạn chú ý nhé, đoạn code trên mình có truyền vào tham số n = 20 nên có hơi chút khác biệt so với các ví dụ ở trên.

4. Multi decorator trong Python

Bạn có thể áp dụng nhiều decorator cho một function.

Ví dụ: Giả sử mình có một hàm

def addStrongTag(func):
    def add(msg):
        print('<strong>')
        func(msg)
        print('</strong>')
    return add

def addSpanTag(func):
    def add(msg):
        print('<span>')
        func(msg)
        print('</span>')
    return add

@addStrongTag
@addSpanTag
def showMessage(msg):
    print(msg)

showMessage("Freetuts.net")

Kết quả:

decorator multi JPG

5. Decorator với class trong Python

Bạn có thể tạo decorator bằng một class với điều kiện trong class đó phải khai báo phương thức __call__ nhé.

class addTag():

    def __init__(self, func):
        self.func = func

    def __call__(self, msg):
        print('<strong>')
        self.func(msg)
        print('</strong>')

@addTag
def showMessage(msg):
    print(msg)

showMessage("freetuts.net")

Kết quả:

<strong>
freetuts.net
</strong>

Kết luận: Qua bài này ta thấy việc sử dụng decorator trong Python thực sự rất hữu ích. Có nhiều trường hợp trong thực tế có thể áp dụng nó như: Chương trình quản lý đăng nhập, quản lý việc hiển thị nội dung ra bên ngoài một trang web ...

Cuối cùng, chúc bạn nắm vững được kỹ thuật decorator này nhé.

Cùng chuyên mục:

Cách lưu trữ và tải lại Models trong PyTorch

Cách lưu trữ và tải lại Models trong PyTorch

Tìm hiểu về TensorBoard với PyTorch

Tìm hiểu về TensorBoard với PyTorch

Học chuyển giao (Transfer Learning) trong PyTorch Beginner

Học chuyển giao (Transfer Learning) trong PyTorch Beginner

Hướng dẫn cơ bản mạng Nơ-ron Tích Chập (CNN) trong PyTorch

Hướng dẫn cơ bản mạng Nơ-ron Tích Chập (CNN) trong PyTorch

Mạng Nơ-Ron truyền thẳng (Feed Forward Neural Network) trong PyTorch

Mạng Nơ-Ron truyền thẳng (Feed Forward Neural Network) trong PyTorch

Tìm hiểu Activation Functions trong PyTorch

Tìm hiểu Activation Functions trong PyTorch

Softmax và Cross Entropy trong PyTorch Beginner

Softmax và Cross Entropy trong PyTorch Beginner

Dataset Transforms trong PyTorch Beginner

Dataset Transforms trong PyTorch Beginner

Dataset và DataLoader trong PyTorch Beginner

Dataset và DataLoader trong PyTorch Beginner

Hồi quy Logistic trong PyTorch Beginner

Hồi quy Logistic trong PyTorch Beginner

Hồi quy tuyến tính trong PyTorch Beginner

Hồi quy tuyến tính trong PyTorch Beginner

Training Pipeline trong PyTorch Beginner

Training Pipeline trong PyTorch Beginner

Sử dụng Gradient Descent với Autograd trong PyTorch

Sử dụng Gradient Descent với Autograd trong PyTorch

Hướng dẫn về Tensor cơ bản trong PyTorch

Hướng dẫn về Tensor cơ bản trong PyTorch

Hướng dẫn cài đặt PyTorch với Deep Learning

Hướng dẫn cài đặt PyTorch với Deep Learning

LDA (Linear Discriminant Analysis) trong Python

LDA (Linear Discriminant Analysis) trong Python

Thuật toán AdaBoost trong Python

Thuật toán AdaBoost trong Python

Thuật toán K-Means Clustering trong Python

Thuật toán K-Means Clustering trong Python

Triển khai PCA bằng Python

Triển khai PCA bằng Python

Triển khai thuật toán Random Forest bằng Python

Triển khai thuật toán Random Forest bằng Python

Top