Last active
November 25, 2016 03:08
-
-
Save itsjef/5f2c539d9e8a0ff712f0214fa634620d to your computer and use it in GitHub Desktop.
The Sublime Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def singleton(cls): | |
| instance = cls() | |
| instance.__call__ = lambda: instance | |
| return instance | |
| @singleton | |
| class A: | |
| def __init__(self): | |
| self.x = 10 | |
| assert A().x == 10 #1 | |
| assert A() is A() #2 | |
| A().x = 15 | |
| assert A().x == 15 #3 | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Giải thích
Hiểu về __metaclass__
Ta biết, mỗi instance là khởi tạo của một class. Vậy tương tự, mỗi class chính là instance của một metaclass.
Có thể nói: "metaclass là class của class"
Khởi tạo class từ metaclass như thế nào?
Trong Python, metaclass mặc định là
type. Khi ta định nghĩa 1 class như sau:đồng nghĩa với việc class A được khởi tạo như sau:
và ta khởi tạo instance của
class Abằng:Nói thêm: Kí tự
Abên trái dấu=chỉ mang nghĩa đặt tên để khởi tạo instance, không nhất thiết phải trùng với tên thật của class. Cách viết như sau không ảnh hưởng gì đến class của instancea:Decorator
Là một method nhận vào một method và trả về một method.
Ví dụ:
Giải thích code
Tương đương với