-
Notifications
You must be signed in to change notification settings - Fork 1
/
new.html
218 lines (201 loc) · 27.5 KB
/
new.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
<!DOCTYPE html>
<html lang="vi">
<head>
<title>Tin tức Python PyMI.vn</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="utf-8" />
<link href="https://n.pymi.vn/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Tin tức Python PyMI.vn Full Atom Feed" />
<!-- twitter card metadata -->
<meta name="twitter:site" content="">
<meta name="twitter:title" content="__new__ và __init__">
<meta name="twitter:description" content="lại một câu hỏi phỏng vấn chán ngắc">
<!-- OG Tags -->
<meta property="og:url" content="./new.html"/>
<meta property="og:title" content="__new__ và __init__ | Tin tức Python PyMI.vn" />
<meta property="og:description" content="lại một câu hỏi phỏng vấn chán ngắc" />
<!-- favicon -->
<!-- moment.js for date formatting -->
<script src="./theme/js/moment.js"></script>
<!-- css -->
<link rel="stylesheet" type="text/css" href="./theme/css/main.css" />
<script>
/*! grunt-grunticon Stylesheet Loader - v2.1.2 | https://github.com/filamentgroup/grunticon | (c) 2015 Scott Jehl, Filament Group, Inc. | MIT license. */
(function(e){function t(t,n,r,o){"use strict";function a(){for(var e,n=0;u.length>n;n++)u[n].href&&u[n].href.indexOf(t)>-1&&(e=!0);e?i.media=r||"all":setTimeout(a)}var i=e.document.createElement("link"),l=n||e.document.getElementsByTagName("script")[0],u=e.document.styleSheets;return i.rel="stylesheet",i.href=t,i.media="only x",i.onload=o||null,l.parentNode.insertBefore(i,l),a(),i}var n=function(r,o){"use strict";if(r&&3===r.length){var a=e.navigator,i=e.Image,l=!(!document.createElementNS||!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect||!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1")||e.opera&&-1===a.userAgent.indexOf("Chrome")||-1!==a.userAgent.indexOf("Series40")),u=new i;u.onerror=function(){n.method="png",n.href=r[2],t(r[2])},u.onload=function(){var e=1===u.width&&1===u.height,a=r[e&&l?0:e?1:2];n.method=e&&l?"svg":e?"datapng":"png",n.href=a,t(a,null,null,o)},u.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",document.documentElement.className+=" grunticon"}};n.loadCSS=t,e.grunticon=n})(this);(function(e,t){"use strict";var n=t.document,r="grunticon:",o=function(e){if(n.attachEvent?"complete"===n.readyState:"loading"!==n.readyState)e();else{var t=!1;n.addEventListener("readystatechange",function(){t||(t=!0,e())},!1)}},a=function(e){return t.document.querySelector('link[href$="'+e+'"]')},c=function(e){var t,n,o,a,c,i,u={};if(t=e.sheet,!t)return u;n=t.cssRules?t.cssRules:t.rules;for(var l=0;n.length>l;l++)o=n[l].cssText,a=r+n[l].selectorText,c=o.split(");")[0].match(/US\-ASCII\,([^"']+)/),c&&c[1]&&(i=decodeURIComponent(c[1]),u[a]=i);return u},i=function(e){var t,o,a;o="data-grunticon-embed";for(var c in e)if(a=c.slice(r.length),t=n.querySelectorAll(a+"["+o+"]"),t.length)for(var i=0;t.length>i;i++)t[i].innerHTML=e[c],t[i].style.backgroundImage="none",t[i].removeAttribute(o);return t},u=function(t){"svg"===e.method&&o(function(){i(c(a(e.href))),"function"==typeof t&&t()})};e.embedIcons=i,e.getCSS=a,e.getIcons=c,e.ready=o,e.svgLoadedCallback=u,e.embedSVG=u})(grunticon,this);
grunticon(["./theme/css/icons.data.svg.css", "./theme/css/icons.data.png.css", "./theme/css/icons.fallback.css"]);
</script>
<noscript><link href="./theme/css/icons.fallback.css" rel="stylesheet"></noscript>
<!-- menu toggle javascript -->
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", initMenu);
function initMenu(){
var menu = document.getElementById("menu");
var menulink = document.getElementById("menu-link");
menulink.addEventListener("click", function toggleMenu(){
window.event.preventDefault();
menulink.classList.toggle('active');
menu.classList.toggle('active');
});
};
</script>
<meta name="description" content="lại một câu hỏi phỏng vấn chán ngắc" />
<meta name="tags" content="python" />
<meta name="tags" content="class" />
</head>
<body>
<div role="banner" id="masthead">
<header>
<h1><a href="/">Pymiers's Blog</a></h1>
<a href="#menu" id="menu-link">more stuff</a>
<nav id="menu">
<ul>
<li><a href="./category/features.html">features</a></li>
<li class="active"><a href="./category/news.html">news</a></li>
<li><a href="./category/pymivn.html">pymi.vn</a></li>
</ul>
</nav>
</header>
</div>
<div class="page" role="main">
<div class="article" role="article">
<article>
<footer>
<a name="top"></a>
<p>
<time datetime=" 2023-05-28 00:00:00+07:00">
<script>document.write(moment('2023-05-28 00:00:00+07:00').format('LL'));</script>
</time>
</p>
</footer>
<header>
<h2>
__new__ và __init__
</h2>
<center>
<h4>
by Pymier0
</h4>
</center>
</header>
<div class="content">
<p><center>
<img alt="new" src="https://images.unsplash.com/photo-1620924049153-4d32fcbe88fe?ixlib=rb-4.0.3&q=85&fm=jpg&crop=entropy&cs=srgb&dl=nick-fewings-1SsUquHPNT8-unsplash.jpg&w=640">
Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Nick Fewings</a> on <a href="https://unsplash.com/photos/1SsUquHPNT8?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
</center></p>
<h3><code>__new__</code> và <code>__init__</code> khác gì?</h3>
<p>Như đa phần các câu hỏi phỏng vấn nặng tính lý thuyết, ít ứng dụng thực tế hay trăm năm dùng 1 lần, đây không là ngoại lệ.</p>
<p>Các câu khác tương tự:</p>
<ul>
<li>decorator là gì (<strong>CHƯA</strong> bao giờ thấy ai hỏi generator dù generator dùng nhiều gấp decorator trăm lần).</li>
<li><span class="caps">GIL</span> là gì, thread với process khác gì nhau, nhược điểm của thread trong Python. (Không thực sự vô dụng, nhưng hiếm dùng với web-developer) Xem câu trả lời ở <a href="https://docs.python.org/3/library/threading.html">https://docs.python.org/3/library/threading.html</a></li>
</ul>
<h3>Python <code>__init__</code></h3>
<p><code>__init__</code> thì ai viết class cũng dùng, method <code>__init__</code> dùng để khởi tạo một object (class instance), ví dụ:</p>
<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">Cat</span><span class="p">():</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">age</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Calling __init__"</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">=</span> <span class="n">age</span>
</code></pre></div>
<h3>Python <code>__new__</code> có hay dùng không?</h3>
<p><code>__new__</code> rất ít khi thấy, vì rất ít được dùng. Thử tìm trong 3 web framework phổ biến nhất của Python: Django, Flask, FastAPI, thấy:</p>
<div class="highlight"><pre><span></span><code><span class="err">$</span> <span class="n">grep</span> <span class="o">-</span><span class="n">Rin</span> <span class="s1">'def __new__'</span> <span class="n">django</span>
<span class="n">django</span><span class="o">/</span><span class="n">tests</span><span class="o">/</span><span class="n">model_forms</span><span class="o">/</span><span class="n">tests</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">3615</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">utils</span><span class="o">/</span><span class="n">datastructures</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">233</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">warning</span><span class="o">=</span><span class="s2">"ImmutableList object is immutable."</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">utils</span><span class="o">/</span><span class="n">deconstruct</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">15</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">utils</span><span class="o">/</span><span class="n">deprecation</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">55</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">test</span><span class="o">/</span><span class="n">selenium</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">23</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">forms</span><span class="o">/</span><span class="n">widgets</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">216</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="n">mcs</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">forms</span><span class="o">/</span><span class="n">models</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">269</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="n">mcs</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">forms</span><span class="o">/</span><span class="n">forms</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">24</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="n">mcs</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">db</span><span class="o">/</span><span class="n">migrations</span><span class="o">/</span><span class="n">operations</span><span class="o">/</span><span class="n">base</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">36</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">db</span><span class="o">/</span><span class="n">migrations</span><span class="o">/</span><span class="n">migration</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">231</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">setting</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">db</span><span class="o">/</span><span class="n">models</span><span class="o">/</span><span class="n">manager</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">21</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">db</span><span class="o">/</span><span class="n">models</span><span class="o">/</span><span class="n">enums</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">12</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="n">metacls</span><span class="p">,</span> <span class="n">classname</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">classdict</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">db</span><span class="o">/</span><span class="n">models</span><span class="o">/</span><span class="n">base</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">95</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="n">attrs</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">django</span><span class="o">/</span><span class="n">django</span><span class="o">/</span><span class="n">conf</span><span class="o">/</span><span class="fm">__init__</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">41</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">setting_name</span><span class="p">):</span>
<span class="err">$</span> <span class="n">grep</span> <span class="o">-</span><span class="n">Rin</span> <span class="s1">'def __new__'</span> <span class="n">flask</span>
<span class="err">$</span> <span class="n">grep</span> <span class="o">-</span><span class="n">Rin</span> <span class="s1">'def __new__'</span> <span class="n">fastapi</span>
<span class="err">$</span> <span class="n">grep</span> <span class="o">-</span><span class="n">Rin</span> <span class="s1">'def __new__'</span> <span class="n">werkzeug</span>
<span class="n">werkzeug</span><span class="o">/</span><span class="n">src</span><span class="o">/</span><span class="n">werkzeug</span><span class="o">/</span><span class="n">urls</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">71</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n">t</span><span class="o">.</span><span class="n">Any</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n">t</span><span class="o">.</span><span class="n">Any</span><span class="p">)</span> <span class="o">-></span> <span class="n">BaseURL</span><span class="p">:</span>
<span class="n">werkzeug</span><span class="o">/</span><span class="n">examples</span><span class="o">/</span><span class="n">cupoftee</span><span class="o">/</span><span class="n">application</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">49</span><span class="p">:</span> <span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="n">metacls</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">this_bases</span><span class="p">,</span> <span class="n">d</span><span class="p">):</span>
</code></pre></div>
<p>Chỉ mình <code>django</code> có viết <code>__new__</code>, 2 framework còn lại không hề thấy, tìm thêm <code>werkzeug</code> (của Flask), thấy 1 ví dụ không quá hữu dụng (để hiện warning deprecate method) werkzeug/src/werkzeug/urls.py:</p>
<div class="highlight"><pre><span></span><code><span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n">t</span><span class="o">.</span><span class="n">Any</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n">t</span><span class="o">.</span><span class="n">Any</span><span class="p">)</span> <span class="o">-></span> <span class="n">BaseURL</span><span class="p">:</span>
<span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span>
<span class="sa">f</span><span class="s2">"'werkzeug.urls.</span><span class="si">{</span><span class="bp">cls</span><span class="o">.</span><span class="vm">__name__</span><span class="si">}</span><span class="s2">' is deprecated and will be removed in"</span>
<span class="s2">" Werkzeug 3.0. Use the 'urllib.parse' library instead."</span><span class="p">,</span>
<span class="ne">DeprecationWarning</span><span class="p">,</span>
<span class="n">stacklevel</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span>
<span class="p">)</span>
<span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</code></pre></div>
<blockquote>
<p><code>__new__()</code> is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.</p>
</blockquote>
<p>Django subclass str:</p>
<div class="highlight"><pre><span></span><code><span class="c1"># django/conf/__init__.py</span>
<span class="k">class</span> <span class="nc">SettingsReference</span><span class="p">(</span><span class="nb">str</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> String subclass which references a current settings value. It's treated as</span>
<span class="sd"> the value in memory but serializes to a settings.NAME attribute reference.</span>
<span class="sd"> """</span>
<span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">setting_name</span><span class="p">):</span>
<span class="k">return</span> <span class="nb">str</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">setting_name</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">setting_name</span> <span class="o">=</span> <span class="n">setting_name</span>
</code></pre></div>
<h3>Python <code>__new__</code> là gì</h3>
<p><code>__new__</code> là một staticmethod (là một trường hợp đặc biệt, nên không cần @staticmethod), dùng để tạo 1 instance của class (tạo object). Sau khi tạo ra object rồi, object gọi <code>__init__</code> để “initialize” (khởi tạo các giá trị).</p>
<div class="highlight"><pre><span></span><code><span class="k">class</span> <span class="nc">Cat</span><span class="p">():</span>
<span class="k">def</span> <span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwarsg</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Calling __new__"</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="bp">cls</span><span class="p">)</span>
<span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">age</span><span class="p">):</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Calling __init__"</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">=</span> <span class="n">age</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">Cat</span><span class="p">(</span><span class="s2">"Meo"</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
</code></pre></div>
<div class="highlight"><pre><span></span><code>Calling __new__
Calling __init__
</code></pre></div>
<blockquote>
<p>Because <code>__new__()</code> and <code>__init__()</code> work together in constructing objects (<code>__new__()</code> to create it, and <code>__init__()</code> to customize it), no non-None value may be returned by <code>__init__()</code></p>
</blockquote>
<p><code>__new__</code> thực hiện việc tạo object, nên có thể đặt các logic đặc biệt về tạo object ở đây, ví dụ chỉ cho phép tạo N object, hay chỉ cho phép tạo 1 object duy nhất (còn gọi là singleton pattern). Ví dụ:</p>
<ul>
<li><a href="https://docs.python.org/3/faq/programming.html?highlight=__new__#how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance">https://docs.python.org/3/faq/programming.html?highlight=__new__#how-can-a-subclass-control-what-data-is-stored-in-an-immutable-instance</a></li>
<li><a href="https://stackoverflow.com/a/8106977">https://stackoverflow.com/a/8106977</a></li>
<li><a href="https://stackoverflow.com/a/8665179">https://stackoverflow.com/a/8665179</a></li>
</ul>
<h3>Kết luận</h3>
<ul>
<li><code>__new__</code> là static method (thuộc về class), <code>__init__</code> là method (thuộc về instance/object)</li>
<li><code>__new__</code> gọi trước, <code>__init__</code> gọi sau</li>
<li><code>__new__</code> trả về instance của class, <code>__init__</code> trả về None</li>
<li><code>__init__</code> ở mọi nơi, <code>__new__</code> ít được dùng.</li>
</ul>
<p>Code Flask hay FastAPI 5 năm, cũng không 1 lần viết <code>__new__</code>!</p>
<h3>Tham khảo</h3>
<ul>
<li><a href="https://docs.python.org/3/reference/datamodel.html?highlight=__new__#object.__new__">https://docs.python.org/3/reference/datamodel.html?highlight=__new__#object.__new__</a></li>
</ul>
<p>Hết.</p>
<p>Đăng ký ngay tại <a href="https://pymi.vn">PyMI.vn</a> để học Python tại Hà Nội <span class="caps">TP</span> <span class="caps">HCM</span> (Sài Gòn),
trở thành lập trình viên #python chuyên nghiệp ngay sau khóa học.</p>
</div>
<div class="back-to-top">
<a href="#top">back to top</a>
</div>
</article>
</div>
<!-- end article -->
<footer>
<div class="icons">
<a href="https://github.com/pymivn" target="_blank"><div class="icon-github icon"></div></a>
</div>
<p>© <script>document.write(moment().format('YYYY'));</script> Pymiers</p>
</footer>
</div>
</body>
</html>