Mọi người cho mình hỏi time.localtime trả về 1 tuple hay instance của 1 class vậy. Mình thấy kết quả ghi là struct nhưng biểu diễn như tuple, còn trên stackoverflow nói nó là instance của 1 class
Lệnh time.localtime trong python trả về 1 tuple hay instance của 1 class?
Mở IDLE, chạy thử xem nó ra cái gì.
>>> import time
>>> x = time.localtime()
>>> x
time.struct_time(tm_year=2019, tm_mon=2, tm_mday=1, tm_hour=17, tm_min=34, tm_sec=41, tm_wday=4, tm_yday=32, tm_isdst=0)
>>> type(x)
<class 'time.struct_time'>
https://docs.python.org/3/library/time.html#time.struct_time
It is an object with a named tuple interface: values can be accessed by index and by attribute name.
named_tuple là immutable (không thể thay đổi)
Gọi tiếp:
>>> x.tm_mon
2
>>> x.tm_mon = 2
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
x.tm_mon = 2
AttributeError: readonly attribute
named tuple của Python là khái niệm trông có vẻ giống struct của các ngôn ngữ khác (truy cập được bằng attribute), nhưng nó lại không thay đổi được giá trị.
Bonus
A named tuple can be a built-in type such as
time.struct_time
, or it can be created with a regular class definition.
1 Like