Đối với tốc độ thuần khiết, không thay đổi và hiệu quả vô biên, các loại thậm chí có thể khiến những người như Chuck Norris tạm dừng và bất lực nhìn vào sự sợ hãi, tôi khiêm tốn đề xuất cách tiếp cận được lên kế hoạch tốt này với
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
2:pure, unadulterated speed and boundless efficiency, the kinds of which could even cause the likes of Chuck Norris to take pause and helplessly look on in awe, I humbly recommend this remarkably well planned-out approach with dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
2:def dict[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
Đối với một lớp xác định thuộc tính
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
3, chẳng hạn như với dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
4, cách tiếp cận trên rất có thể sẽ không hoạt động, vì thuộc tính dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
2 sẽ không có sẵn trên các trường hợp lớp. Trong trường hợp đó, một cách tiếp cận "bắn cho mặt trăng" hiệu quả cao như dưới đây có thể là khả thi:dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
3 attribute, such as with dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
4, the above approach most likely won't work, as the dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
2
attribute won't be available on class instances. In that case, a highly efficient "shoot for the moon" approach such as below could instead be viable:def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
Trong trường hợp bất kỳ ai đang ở rìa ghế của họ ngay bây giờ [tôi biết, điều này thực sự đáng kinh ngạc, những thứ đột phá] - Tôi đã thêm thời gian cá nhân của mình thông qua mô -đun
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
6 bên dưới, hy vọng sẽ làm sáng tỏ hơn một chút trong Khía cạnh hiệu suất của mọi thứ.FYI, các cách tiếp cận với
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
2 thuần túy chắc chắn nhanh hơn nhiều so với dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
8.Lưu ý: Mặc dù
2 hoạt động tốt hơn trong trường hợp cụ thể này,dict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
8 có thể sẽ tốt hơn cho các từ điển tổng hợp, chẳng hạn như các dữ liệu có các dữ liệu lồng nhau hoặc các giá trị có các loại có thể thay đổi nhưdict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand1 hoặcfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand2.
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
Kết quả trên máy tính xách tay Mac M1 của tôi:
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
Mã nguồn: lib/dataclasses.py Lib/dataclasses.py
Mô-đun này cung cấp một bộ trang trí và chức năng để tự động thêm các phương thức đặc biệt được tạo như
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 và
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand4 vào các lớp do người dùng xác định. Nó ban đầu được mô tả trong PEP 557.special methods such as
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 and
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand4 to user-defined classes. It was originally described in PEP 557.
Các biến thành viên để sử dụng trong các phương thức được tạo này được xác định bằng cách sử dụng các chú thích loại PEP 526. Ví dụ: mã này:PEP 526 type annotations. For example, this code:
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
Sẽ thêm, trong số những thứ khác, một
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 trông giống như:
def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand
Lưu ý rằng phương pháp này được tự động thêm vào lớp: nó không được chỉ định trực tiếp trong định nghĩa
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand6 được hiển thị ở trên.
Mới trong phiên bản 3.7.
Nội dung mô -đun
@dataclasses.dataclass [*, init = true, repr = true, eq = true, order = false, unsafe_hash = false, frozen = false, match_args = truedataclasses.dataclass[*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False]¶Hàm này là một nhà trang trí được sử dụng để thêm các phương pháp đặc biệt được tạo vào các lớp, như được mô tả dưới đây.decorator that is used to add generated special methods to classes, as described below.
Người trang trí
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 kiểm tra lớp học để tìm
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand8s. Một
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand8 được định nghĩa là một biến lớp có chú thích loại. Với hai trường hợp ngoại lệ được mô tả dưới đây, không có gì trong
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 kiểm tra loại được chỉ định trong chú thích biến.type annotation. With two exceptions described below, nothing in
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 examines the type specified in the variable annotation.
Thứ tự của các trường trong tất cả các phương thức được tạo là thứ tự chúng xuất hiện trong định nghĩa lớp.
Nhà trang trí
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 sẽ thêm các phương pháp khác nhau của Dunder vào lớp, được mô tả dưới đây. Nếu bất kỳ phương thức được thêm nào đã tồn tại trong lớp, hành vi phụ thuộc vào tham số, như được ghi lại dưới đây. Người trang trí trả lại cùng một lớp mà nó được gọi trên; Không có lớp mới được tạo ra.
Nếu
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 được sử dụng như một trình trang trí đơn giản không có tham số, nó hoạt động như thể nó có các giá trị mặc định được ghi lại trong chữ ký này. Đó là, ba cách sử dụng
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 này tương đương:
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
Các tham số đến
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 là:
def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand
5: Nếu đúng [mặc định], phương thứcfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3 sẽ được tạo.Nếu lớp đã xác định
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3, tham số này sẽ bị bỏ qua.def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand
8: Nếu đúng [mặc định], phương thứcfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
4 sẽ được tạo. Chuỗi repr được tạo sẽ có tên lớp và tên và repr của mỗi trường, theo thứ tự chúng được xác định trong lớp. Các trường được đánh dấu là bị loại trừ khỏi repr không được bao gồm. Ví dụ:@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
0.Nếu lớp đã xác định
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
4, tham số này sẽ bị bỏ qua.@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
2: Nếu đúng [mặc định], phương thức@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
3 sẽ được tạo. Phương pháp này so sánh lớp như thể nó là một bộ của các trường của nó, theo thứ tự. Cả hai trường hợp trong so sánh phải thuộc loại giống hệt nhau.Nếu lớp đã xác định
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
3, tham số này sẽ bị bỏ qua.@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
5: Nếu đúng [mặc định là@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
6],@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
7,@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
8,@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
9 và@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
0 sẽ được tạo ra. Chúng so sánh lớp như thể nó là một bộ phận của các trường của nó, theo thứ tự. Cả hai trường hợp trong so sánh phải thuộc loại giống hệt nhau. Nếu@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
5 là đúng và@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
2 là sai, thì@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
3 sẽ được nâng lên.Nếu lớp đã xác định bất kỳ
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
7,@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
8,@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
9 hoặc@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
0, thì@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
8 sẽ được nâng lên.@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
9: Nếu@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
6 [mặc định], phương thứcdef __init__[self, a: int, b: int = 0]:
1 được tạo theo cách@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
2 vàdef __init__[self, a: int, b: int = 0]:
3 được đặt.def __init__[self, a: int, b: int = 0]:
1 được sử dụng bởidef __init__[self, a: int, b: int = 0]:
5 tích hợp và khi các đối tượng được thêm vào các bộ sưu tập băm như từ điển và bộ. Có mộtdef __init__[self, a: int, b: int = 0]:
1 ngụ ý rằng các trường hợp của lớp là bất biến. Khả năng đột biến là một tài sản phức tạp phụ thuộc vào ý định của lập trình viên, sự tồn tại và hành vi của@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
3 và các giá trị của các cờ@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
2 vàdef __init__[self, a: int, b: int = 0]:
3 trong bộ trang trífrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
7.Theo mặc định,
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
7 sẽ không ngầm thêm phương thứcdef __init__[self, a: int, b: int = 0]:
1 trừ khi an toàn để làm như vậy. Nó sẽ không thêm hoặc thay đổi một phương thứcdef __init__[self, a: int, b: int = 0]:
1 được xác định rõ ràng hiện có. Đặt thuộc tính lớp@dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]
4 có một ý nghĩa cụ thể đối với Python, như được mô tả trong tài liệudef __init__[self, a: int, b: int = 0]:
1.Nếu
def __init__[self, a: int, b: int = 0]:
1 không được xác định rõ ràng hoặc nếu nó được đặt thành@dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]
7, thìfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
7 có thể thêm một phương thứcdef __init__[self, a: int, b: int = 0]:
1 ngầm. Mặc dù không được khuyến nghị, bạn có thể buộcfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
7 để tạo phương thứcdef __init__[self, a: int, b: int = 0]:
1 với
02. Đây có thể là trường hợp nếu lớp của bạn là bất biến về mặt logic nhưng dù sao cũng có thể bị đột biến. Đây là một trường hợp sử dụng chuyên ngành và nên được xem xét cẩn thận.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
Dưới đây là các quy tắc quản lý việc tạo ra một phương pháp
def __init__[self, a: int, b: int = 0]:
1. Lưu ý rằng cả hai bạn không thể có một phương thứcdef __init__[self, a: int, b: int = 0]:
1 rõ ràng trong DataClass của bạn và đặt
02; Điều này sẽ dẫn đếndef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
8.Nếu
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
2 vàdef __init__[self, a: int, b: int = 0]:
3 đều đúng, theo mặc định,from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
7 sẽ tạo phương thứcdef __init__[self, a: int, b: int = 0]:
1 cho bạn. Nếu@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
2 là đúng vàdef __init__[self, a: int, b: int = 0]:
3 là sai,def __init__[self, a: int, b: int = 0]:
1 sẽ được đặt thành@dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]
7, đánh dấu nó không thể vượt qua [đó là, vì nó là có thể thay đổi]. Nếu@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
2 là sai,def __init__[self, a: int, b: int = 0]:
1 sẽ không bị ảnh hưởng có nghĩa là phương phápdef __init__[self, a: int, b: int = 0]:
1 của siêu lớp sẽ được sử dụng [nếu siêu lớp là
18, điều này có nghĩa là nó sẽ quay trở lại băm dựa trên ID].def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
def __init__[self, a: int, b: int = 0]:
3: Nếu đúng [mặc định là@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
6], việc gán cho các trường sẽ tạo ra một ngoại lệ. Điều này mô phỏng các trường hợp đông lạnh chỉ đọc. Nếu
21 hoặcdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
22 được xác định trong lớp, thìdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
8 sẽ được nâng lên. Xem các cuộc thảo luận dưới đây.
24: Nếu đúng [mặc định làdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
25], tpledef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
26 sẽ được tạo từ danh sách các tham số đến phương thứcdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3 được tạo [ngay cả khifrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3 không được tạo, xem ở trên]. Nếu sai, hoặc nếu
26 đã được xác định trong lớp, thìdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
26 sẽ không được tạo.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
31: Nếu đúng [giá trị mặc định làdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
6], thì tất cả các trường sẽ được đánh dấu là chỉ từ khóa. Nếu một trường được đánh dấu là chỉ từ khóa, thì hiệu ứng duy nhất là tham sốfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3 được tạo từ trường chỉ từ khóa phải được chỉ định với từ khóa khifrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3 được gọi. Không có ảnh hưởng đến bất kỳ khía cạnh nào khác của DataClasses. Xem mục nhập bảng chú số để biết chi tiết. Cũng xem phần
35.parameter glossary entry for details. Also see thedef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
35 section.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
36: Nếu đúng [mặc định làdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
6], thuộc tính
38 sẽ được tạo và lớp mới sẽ được trả về thay vì bản gốc. Nếudef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 đã được xác định trong lớp, thìdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
8 sẽ được nâng lên.
Mới trong phiên bản 3.10.
Đã thay đổi trong phiên bản 3.11: Nếu một tên trường đã được bao gồm trong
38 của một lớp cơ sở, thì nó sẽ không được đưa vàodef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 được tạo để ngăn chặn chúng. Do đó, không sử dụngdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 để truy xuất tên trường của DataClass. Sử dụngdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
44 thay thế. Để có thể xác định các vị trí di truyền, lớp cơ sởdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 có thể là bất kỳ điều gì có thể lặp lại, nhưng không phải là một trình lặp.If a field name is already included in thedef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 of a base class, it will not be included in the generateddef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 to prevent overriding them. Therefore, do not usedef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 to retrieve the field names of a dataclass. Usedef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
44 instead. To be able to determine inherited slots, base classdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
38 may be any iterable, but not an iterator.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
46: Nếu đúng [mặc định làdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
6], hãy thêm một khe có tên là __weakref__, được yêu cầu để tạo một trường hợp yếu. Đó là một lỗi để chỉ định
48 mà không chỉ địnhdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
49.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand8S có thể tùy ý chỉ định giá trị mặc định, sử dụng cú pháp Python bình thường:
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'
Trong ví dụ này, cả
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
51 và def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
52 sẽ được bao gồm trong phương thức from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được thêm vào, sẽ được định nghĩa là:
def __init__[self, a: int, b: int = 0]:
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8 sẽ được nâng lên nếu một trường không có giá trị mặc định theo trường có giá trị mặc định. Điều này đúng cho dù điều này xảy ra trong một lớp duy nhất, hoặc là kết quả của kế thừa lớp học. dataClasses.field [*, mặc định = thiếu, default_factory = thiếu, init = true, repr = true, hash = none, so sánh = true, metadata = none, kw_only = thiếu]field[*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING]¶
Đối với các trường hợp sử dụng thông thường và đơn giản, không có chức năng nào khác là bắt buộc. Tuy nhiên, có một số tính năng DataClass yêu cầu thêm thông tin trên mỗi trường. Để đáp ứng nhu cầu này để biết thêm thông tin, bạn có thể thay thế giá trị trường mặc định bằng một cuộc gọi đến hàm
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
55 được cung cấp. Ví dụ:@dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]
Như được hiển thị ở trên, giá trị
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
56 là đối tượng Sentinel được sử dụng để phát hiện nếu một số tham số được cung cấp bởi người dùng. Sentinel này được sử dụng vì @dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]7 là một giá trị hợp lệ cho một số tham số có ý nghĩa riêng biệt. Không có mã nào nên trực tiếp sử dụng giá trị
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
56.Các tham số đến
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
55 là:
60: Nếu được cung cấp, đây sẽ là giá trị mặc định cho trường này. Điều này là cần thiết vìdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
55 tự gọi thay thế vị trí bình thường của giá trị mặc định.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
62: Nếu được cung cấp, nó phải là một cuộc gọi không có thể gọi được sẽ được gọi khi cần giá trị mặc định cho trường này. Trong số các mục đích khác, điều này có thể được sử dụng để chỉ định các trường có các giá trị mặc định có thể thay đổi, như được thảo luận dưới đây. Đó là một lỗi để chỉ định cảdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
60 vàdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
62.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand
5: Nếu đúng [mặc định], trường này được bao gồm dưới dạng tham số cho phương thứcfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3 được tạo.def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand
8: Nếu đúng [mặc định], trường này được bao gồm trong chuỗi được trả về bởi phương thứcfrom dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
4 được tạo.
69: Đây có thể là bool hoặcdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]
7. Nếu đúng, trường này được bao gồm trong phương thứcdef __init__[self, a: int, b: int = 0]:
1 được tạo. Nếu@dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]
7 [mặc định], hãy sử dụng giá trị của
73: Đây thường là hành vi mong đợi. Một lĩnh vực nên được xem xét trong băm nếu nó được sử dụng để so sánh. Đặt giá trị này thành bất cứ điều gì khác ngoàidef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: mylist: list[int] = field[default_factory=list] c = C[] c.mylist += [1, 2, 3]
7 không được khuyến khích.Một lý do có thể để đặt
75 Nhưngdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
76 sẽ là nếu một trường tốn kém để tính giá trị băm cho, trường đó là cần thiết để kiểm tra bình đẳng và có các trường khác đóng góp vào giá trị băm kiểu loại. Ngay cả khi một trường được loại trừ khỏi băm, nó vẫn sẽ được sử dụng để so sánh.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
73: Nếu đúng [mặc định], trường này được bao gồm trong các phương thức công bằng và so sánh được tạo [def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
3,@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...
9, et al.].
80: Đây có thể là một ánh xạ hoặc không có. Không ai được coi là một dict trống rỗng. Giá trị này được bọc trongdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
81 để làm cho nó chỉ đọc và tiếp xúc trên đối tượngdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
82. Nó hoàn toàn không được sử dụng bởi các lớp dữ liệu và được cung cấp như một cơ chế mở rộng của bên thứ ba. Nhiều bên thứ ba có thể có chìa khóa riêng, để sử dụng làm không gian tên trong siêu dữ liệu.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
31: Nếu đúng, trường này sẽ được đánh dấu là chỉ từ khóa. Điều này được sử dụng khi các tham số phương thứcdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand
3 được tạo được tính toán.
Nếu giá trị mặc định của trường được chỉ định bởi một cuộc gọi đến
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
55, thì thuộc tính lớp cho trường này sẽ được thay thế bằng giá trị def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
60 được chỉ định. Nếu không có def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
60 được cung cấp, thì thuộc tính lớp sẽ bị xóa. Mục đích là sau khi trình trang trí from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 chạy, các thuộc tính lớp đều sẽ chứa các giá trị mặc định cho các trường, giống như chính giá trị mặc định được chỉ định. Ví dụ, sau:
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
0Thuộc tính lớp
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
89 sẽ là def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
90, thuộc tính lớp def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
91 sẽ là def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
92 và các thuộc tính lớp def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
93 và def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
94 sẽ không được đặt.
classdataclasses.field¶dataclasses.Field¶def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
82 Các đối tượng mô tả từng trường được xác định. Các đối tượng này được tạo bên trong và được trả về bằng phương pháp cấp độ mô-đun def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
44 [xem bên dưới]. Người dùng không bao giờ nên khởi tạo trực tiếp đối tượng def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
82. Các thuộc tính được ghi lại của nó là:
98: Tên của trường.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
99: Loại trường.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
60,def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
62,def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand5,def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand8,69,def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
73,def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
80 vàdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
31 có ý nghĩa và giá trị giống hệt như chúng trong hàmdef dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
55.def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self]
Các thuộc tính khác có thể tồn tại, nhưng chúng là riêng tư và không được kiểm tra hoặc dựa vào.
DataClasses.fields [class_or_instance] ¶fields[class_or_instance]¶Trả về một tuple của các đối tượng
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
82 xác định các trường cho dữ liệu này. Chấp nhận một dữ liệu hoặc một thể hiện của một DataClass. Tăng @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8 nếu không được thông qua một dữ liệu hoặc thể hiện của một. Không trả lại các trường giả là
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
11 hoặc from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
12. dataClasses.asdict [obj, *, dict_factory = dict] ¶asdict[obj,
*, dict_factory=dict]¶Chuyển đổi DataClass
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13 thành Dict [bằng cách sử dụng hàm nhà máy from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
14]. Mỗi DataClass được chuyển đổi thành một mô tả của các trường của nó, dưới dạng các cặp from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
15. DataClasses, dicts, danh sách và bộ dữ liệu được đệ quy vào. Các đối tượng khác được sao chép với from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
16.Ví dụ về việc sử dụng
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
17 trên các dữ liệu lồng nhau:def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
1Để tạo một bản sao nông, cách giải quyết sau đây có thể được sử dụng:
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
2from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
17 tăng @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8 nếu
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13 không phải là một thể hiện dữ liệu. dataclasses.astuple [obj, *, tuple_factory = tuple] ¶astuple[obj,
*, tuple_factory=tuple]¶Chuyển đổi DataClass
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13 thành Tuple [bằng cách sử dụng hàm nhà máy from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
22]. Mỗi DataClass được chuyển đổi thành một bộ của các giá trị trường của nó. DataClasses, dicts, danh sách và bộ dữ liệu được đệ quy vào. Các đối tượng khác được sao chép với from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
16.Tiếp tục từ ví dụ trước:
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
3Để tạo một bản sao nông, cách giải quyết sau đây có thể được sử dụng:
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
4from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
17 tăng @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8 nếu
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13 không phải là một thể hiện dữ liệu. dataclasses.astuple [obj, *, tuple_factory = tuple] ¶make_dataclass[cls_name, fields, *,
bases=[], namespace=None, init=True, repr=True, eq=True,
order=False, unsafe_hash=False, frozen=False, match_args=True,
kw_only=False, slots=False, weakref_slot=False]¶Chuyển đổi DataClass
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13 thành Tuple [bằng cách sử dụng hàm nhà máy from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
22]. Mỗi DataClass được chuyển đổi thành một bộ của các giá trị trường của nó. DataClasses, dicts, danh sách và bộ dữ liệu được đệ quy vào. Các đối tượng khác được sao chép với from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
16.Tiếp tục từ ví dụ trước:
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
5from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
24 tăng @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8 nếu
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13 không phải là một thể hiện dữ liệu.def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
6 dataclasses.make_dataclass [cls_name, trường, *, bases = [], không gian tên = none, init = true, repr = true, eq = true , slots = false, feadref_slot = false] ¶replace[obj, /,
**changes]¶Tạo một dữ liệu mới với tên
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
27, các trường như được định nghĩa trong from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
28, các lớp cơ sở như được đưa ra trong from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
29 và khởi tạo bằng một không gian tên như được đưa ra trong from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
30. from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
28 là một yếu tố có thể có các phần tử là def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
98, from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
33 hoặc from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
34. Nếu chỉ def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
98 được cung cấp, from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
36 được sử dụng cho def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
99. Các giá trị của def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand5,
def __init__[self, name: str, unit_price: float, quantity_on_hand: int = 0]: self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand8,
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...2,
@dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...5,
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'9,
def __init__[self, a: int, b: int = 0]:3,
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
24, def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
31, def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
36 và def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
46 có ý nghĩa tương tự như chúng trong from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7.
Chức năng này không được yêu cầu nghiêm ngặt, bởi vì bất kỳ cơ chế Python nào để tạo một lớp mới với
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
49 sau đó có thể áp dụng hàm from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 để chuyển đổi lớp đó thành DataClass. Hàm này được cung cấp như một sự tiện lợi. Ví dụ:
Tương đương với:
DataClasses.Replace [obj, /, ** thay đổi] ¶
Tạo một đối tượng mới cùng loại với
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13, thay thế các trường bằng các giá trị từ from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
52. Nếu from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
13 không phải là một lớp dữ liệu, hãy tăng @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8. Nếu các giá trị trong
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
52 không chỉ định các trường, tăng @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8. Đối tượng mới được trả về được tạo bằng cách gọi phương thức
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 của DataClass. Điều này đảm bảo rằng
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58, nếu có, cũng được gọi.is_dataclass[obj]¶Các biến chỉ dành cho ban đầu không có giá trị mặc định, nếu có, phải được chỉ định trong cuộc gọi đến
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
59 để chúng có thể được chuyển đến from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 và
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58.Đó là một lỗi cho
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
52 để chứa bất kỳ trường nào được xác định là có from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
63. Một @dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'3 sẽ được nêu ra trong trường hợp này.
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
7 Được báo trước về cách các lĩnh vực from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
63 hoạt động trong một cuộc gọi đến from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
59. Chúng không được sao chép từ đối tượng nguồn, mà được khởi tạo trong from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58, nếu chúng được khởi tạo. Dự kiến các lĩnh vực from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
63 sẽ hiếm khi được sử dụng một cách thận trọng và thận trọng. Nếu chúng được sử dụng, có thể là khôn ngoan khi có các hàm tạo lớp thay thế hoặc có lẽ là phương thức from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
59 [hoặc được đặt tên tương tự] tùy chỉnh để xử lý việc sao chép phiên bản.MISSING¶dataclasses.is_dataclass [obj] ¶
Trả vềdef dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
25 Nếu tham số của nó là một dữ liệu hoặc một thể hiện của một, nếu không hãy trả về @dataclass class C: ... @dataclass[] class C: ... @dataclass[init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False] class C: ...6.KW_ONLY¶
Nếu bạn cần biết liệu một lớp có phải là một thể hiện của một dữ liệu [và không phải là chính dữ liệu], thì hãy thêm kiểm tra thêm cho
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
72:Trong ví dụ này, các trường
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
78 và from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
79 sẽ được đánh dấu là các trường chỉ từ khóa:def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
8Trong một DataClass duy nhất, đó là một lỗi để chỉ định nhiều hơn một trường có loại là
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
35.Mới trong phiên bản 3.10.
ExceptionDataClass.FrozenInstanceError¶dataclasses.FrozenInstanceError¶Lớn lên khi một
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
21 hoặc def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
22 được xác định ngầm được gọi trên một dữ liệu được xác định với from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
83. Nó là một lớp con của from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
84.Xử lý sau khi khởi động
Mã
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tạo sẽ gọi một phương thức có tên
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58, nếu from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58 được xác định trên lớp. Nó thường sẽ được gọi là from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
88. Tuy nhiên, nếu bất kỳ trường from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
12 nào được xác định, chúng cũng sẽ được chuyển đến from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58 theo thứ tự chúng được xác định trong lớp. Nếu không có phương thức from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tạo, thì
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58 sẽ không được gọi tự động.Trong số các mục đích sử dụng khác, điều này cho phép khởi tạo các giá trị trường phụ thuộc vào một hoặc nhiều trường khác. Ví dụ:
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
9Phương pháp
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tạo bởi
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 không gọi các phương thức lớp cơ sở
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3. Nếu lớp cơ sở có phương thức
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 phải được gọi, thì thông thường gọi phương thức này theo phương thức
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58:from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
0Tuy nhiên, lưu ý rằng nói chung, các phương thức
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 do DataClass tạo ra không cần phải gọi, vì DataClass dẫn xuất sẽ chăm sóc việc khởi tạo tất cả các trường của bất kỳ lớp cơ sở nào là chính dữ liệu.
Xem phần bên dưới trên các biến chỉ dành cho init để biết các cách để chuyển các tham số sang
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58. Cũng xem cảnh báo về cách from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
59 xử lý các trường from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
63.Biến lớp
Một trong hai nơi
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 thực sự kiểm tra loại trường là xác định xem một trường có phải là biến lớp như được định nghĩa trong PEP 526 hay không. Nó làm điều này bằng cách kiểm tra xem loại trường là
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
03. Nếu một trường là một from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
11, nó sẽ bị loại trừ khỏi việc xem xét như một trường và bị bỏ qua bởi các cơ chế dữ liệu. Các trường giả from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
11 như vậy không được trả về bởi hàm def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
44 ở cấp độ mô-đun.PEP 526. It does this by checking if the type of the field is dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
03. If a field is a from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
11, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
11 pseudo-fields are not returned by the module-level def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
44
function.Biến chỉ khởi động
Nơi khác mà
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 kiểm tra chú thích loại là để xác định xem một trường có phải là biến chỉ dành cho ban đầu hay không. Nó làm điều này bằng cách xem liệu loại trường thuộc loại
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
08. Nếu một trường là một from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
12, nó được coi là một trường giả được gọi là một trường chỉ dành cho người khởi động. Vì nó không phải là một trường thực sự, nó không được trả về bởi hàm def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
44 ở cấp độ mô-đun. Các trường chỉ dành cho init được thêm vào làm tham số vào phương thức from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tạo và được chuyển sang phương thức
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
58 tùy chọn. Chúng không được sử dụng bởi các dữ liệu.Ví dụ: giả sử một trường sẽ được khởi tạo từ cơ sở dữ liệu, nếu một giá trị không được cung cấp khi tạo lớp:
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
1Trong trường hợp này,
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
44 sẽ trả về def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
82 Đối tượng cho dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
15 và dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
16, nhưng không phải cho dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
17.Các trường hợp đóng băng
Không thể tạo ra các đối tượng Python thực sự bất biến. Tuy nhiên, bằng cách chuyển
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
83 cho người trang trí from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7, bạn có thể mô phỏng tính bất biến. Trong trường hợp đó, DataClasses sẽ thêm các phương thức
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
21 và def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
22 vào lớp. Các phương pháp này sẽ tăng dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
22 khi được gọi.Có một hình phạt hiệu suất nhỏ khi sử dụng
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
83: from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 không thể sử dụng gán đơn giản để khởi tạo các trường và phải sử dụng
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
25.Di sản¶
Khi DataClass được tạo bởi trình trang trí
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7, nó sẽ xem qua tất cả các lớp cơ sở của lớp trong MRO ngược [nghĩa là bắt đầu từ ____118] và, đối với mỗi dữ liệu mà nó tìm thấy, thêm các trường từ lớp cơ sở đó vào một lớp lập bản đồ các lĩnh vực. Sau khi tất cả các trường lớp cơ sở được thêm vào, nó sẽ thêm các trường riêng vào ánh xạ được đặt hàng. Tất cả các phương thức được tạo sẽ sử dụng ánh xạ kết hợp, được tính toán của các trường. Bởi vì các trường theo thứ tự chèn, các lớp dẫn xuất ghi đè các lớp cơ sở. Một ví dụ:
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
2Danh sách cuối cùng của các trường là, theo thứ tự,
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
28, from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
78, from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
79. Loại cuối cùng của dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
28 là dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
32, như được chỉ định trong lớp dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
33.Phương thức
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tạo cho
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
33 sẽ trông giống như:
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
3Đặt hàng lại các tham số chỉ từ khóa trong ________ 43¶
Sau khi các tham số cần thiết cho
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tính toán, bất kỳ tham số chỉ từ khóa nào cũng được di chuyển đến sau tất cả các tham số thông thường [không chỉ KEYWORD]. Đây là một yêu cầu về cách thực hiện các tham số chỉ từ khóa trong Python: chúng phải đến sau các tham số không chỉ dành cho Keyword.
Trong ví dụ này,
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
38, dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
39 và dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
40 là các trường chỉ có từ khóa và dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
41 và dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
42 là các trường thường xuyên:from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
4Phương thức
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tạo cho
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
44 sẽ trông giống như:from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
5Lưu ý rằng các tham số đã được đặt hàng lại từ cách chúng xuất hiện trong danh sách các trường: các tham số có nguồn gốc từ các trường thông thường được theo sau bởi các tham số có nguồn gốc từ các trường chỉ từ khóa.
Thứ tự tương đối của các tham số chỉ từ khóa được duy trì trong danh sách tham số
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được đặt hàng lại.
Các chức năng nhà máy mặc định
Nếu
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
55 chỉ định def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
62, nó được gọi bằng không đối số khi cần giá trị mặc định cho trường. Ví dụ: để tạo một thể hiện mới của danh sách, sử dụng:from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
6Nếu một trường được loại trừ khỏi
from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 [sử dụng
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
63] và trường cũng chỉ định def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
62, thì hàm nhà máy mặc định sẽ luôn được gọi từ hàm from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand3 được tạo. Điều này xảy ra bởi vì không có cách nào khác để cung cấp cho trường một giá trị ban đầu.
Giá trị mặc định có thể thay đổi
Python lưu trữ các giá trị biến thành viên mặc định trong các thuộc tính lớp. Hãy xem xét ví dụ này, không sử dụng DataClasses:
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
7Lưu ý rằng hai trường hợp của lớp
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
33 chia sẻ cùng một biến lớp dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
28, như mong đợi.Sử dụng DataClasses, nếu mã này hợp lệ:
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
8Nó sẽ tạo mã tương tự như:
from dataclasses import dataclass, asdict, field
from uuid import UUID, uuid4
class DictMixin:
"""Mixin class to add a `dict[]` method on classes that define a __slots__ attribute"""
def dict[self]:
body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id'
else f'self.{f}'] for f in self.__slots__]
# Compute the text of the entire function.
txt = f'def dict[self]:\n return {{{body_lines}}}'
ns = {}
exec[txt, locals[], ns]
_dict_fn = self.__class__.dict = ns['dict']
return _dict_fn[self]
@dataclass
class MessageHeader:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict1[self]:
_dict = self.__dict__.copy[]
_dict['message_id'] = str[_dict['message_id']]
return _dict
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in self.__dict__.items[]}
def dict3[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
@dataclass[slots=True]
class MessageHeaderWithSlots[DictMixin]:
message_id: UUID = field[default_factory=uuid4]
string: str = 'a string'
integer: int = 1000
floating: float = 1.0
def dict2[self]:
return {k: str[v] if k == 'message_id' else v
for k, v in asdict[self].items[]}
if __name__ == '__main__':
from timeit import timeit
header = MessageHeader[]
header_with_slots = MessageHeaderWithSlots[]
n = 10000
print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]]
print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]]
print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]]
print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]]
print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]]
print[]
dict__ = header.dict1[]
print[dict__]
asdict__ = header.dict3[]
print[asdict__]
assert isinstance[dict__['message_id'], str]
assert isinstance[dict__['integer'], int]
assert header.dict1[] == header.dict2[] == header.dict3[]
assert header_with_slots.dict[] == header_with_slots.dict2[]
9Điều này có vấn đề tương tự như ví dụ ban đầu sử dụng lớp
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
33. Nghĩa là, hai trường hợp của lớp dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
44 không chỉ định giá trị cho dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
28 khi tạo một thể hiện lớp sẽ chia sẻ cùng một bản sao của dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
28. Bởi vì DataClass chỉ sử dụng tạo lớp Python bình thường, họ cũng chia sẻ hành vi này. Không có cách nào chung cho các lớp dữ liệu để phát hiện điều kiện này. Thay vào đó, người trang trí from dataclasses import dataclass @dataclass class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 def total_cost[self] -> float: return self.unit_price * self.quantity_on_hand7 sẽ tăng
@dataclass class C: a: int # 'a' has no default value b: int = 0 # assign a default value for 'b'8 nếu nó phát hiện một tham số mặc định không thể đo lường được. Giả định là nếu một giá trị là không thể không thể thay đổi được. Đây là một giải pháp một phần, nhưng nó bảo vệ chống lại nhiều lỗi phổ biến.
Sử dụng các hàm nhà máy mặc định là một cách để tạo các phiên bản mới của các loại có thể thay đổi làm giá trị mặc định cho các trường:
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
0Đã thay đổi trong phiên bản 3.11: Thay vì tìm kiếm và loại bỏ các đối tượng thuộc loại
60, dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
61 hoặc dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
62, các đối tượng không thể không thể được phép làm giá trị mặc định. Khả năng không thể sử dụng để gần đúng khả năng đột biến.Instead of looking for and disallowing objects of type dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
60, dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
61, or dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
62, unhashable objects are now not allowed as default values. Unhashability is used to approximate mutability.Các lĩnh vực mô tả kiểu
Các trường được gán các đối tượng mô tả vì giá trị mặc định của chúng có các hành vi đặc biệt sau:descriptor objects as their default value have the following special behaviors:
Giá trị cho trường được chuyển đến phương thức DataClass từ
63 được chuyển cho phương thức mô tả ____ ____364 thay vì ghi đè lên đối tượng mô tả.dict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
Tương tự, khi nhận hoặc đặt trường, phương thức mô tả
65 hoặcdict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
64 được gọi là thay vì trả về hoặc ghi đè đối tượng mô tả.dict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
Để xác định xem một trường có chứa giá trị mặc định hay không,
67 sẽ gọi phương thứcdict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
65 của bộ mô tả bằng mẫu truy cập lớp của nó [nghĩa làdict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
69. Nếu mô tả trả về giá trị trong trường hợp này, nó sẽ được sử dụng làm mặc định của trường. Nếu mô tả tăngdict1[]: 0.005992999998852611 dict2[]: 0.00800508284009993 dict3[]: 0.07069579092785716 slots -> dict[]: 0.00583599996753037 slots -> dict2[]: 0.07395245810039341 {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0} {'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
84 trong tình huống này, sẽ không có giá trị mặc định nào được cung cấp cho trường.from dataclasses import dataclass, asdict, field from uuid import UUID, uuid4 class DictMixin: """Mixin class to add a `dict[]` method on classes that define a __slots__ attribute""" def dict[self]: body_lines = ','.join[f"'{f}':" + [f'str[self.{f}]' if f == 'message_id' else f'self.{f}'] for f in self.__slots__] # Compute the text of the entire function. txt = f'def dict[self]:\n return {{{body_lines}}}' ns = {} exec[txt, locals[], ns] _dict_fn = self.__class__.dict = ns['dict'] return _dict_fn[self] @dataclass class MessageHeader: message_id: UUID = field[default_factory=uuid4] string: str = 'a string' integer: int = 1000 floating: float = 1.0 def dict1[self]: _dict = self.__dict__.copy[] _dict['message_id'] = str[_dict['message_id']] return _dict def dict2[self]: return {k: str[v] if k == 'message_id' else v for k, v in self.__dict__.items[]} def dict3[self]: return {k: str[v] if k == 'message_id' else v for k, v in asdict[self].items[]} @dataclass[slots=True] class MessageHeaderWithSlots[DictMixin]: message_id: UUID = field[default_factory=uuid4] string: str = 'a string' integer: int = 1000 floating: float = 1.0 def dict2[self]: return {k: str[v] if k == 'message_id' else v for k, v in asdict[self].items[]} if __name__ == '__main__': from timeit import timeit header = MessageHeader[] header_with_slots = MessageHeaderWithSlots[] n = 10000 print['dict1[]: ', timeit['header.dict1[]', number=n, globals=globals[]]] print['dict2[]: ', timeit['header.dict2[]', number=n, globals=globals[]]] print['dict3[]: ', timeit['header.dict3[]', number=n, globals=globals[]]] print['slots -> dict[]: ', timeit['header_with_slots.dict[]', number=n, globals=globals[]]] print['slots -> dict2[]: ', timeit['header_with_slots.dict2[]', number=n, globals=globals[]]] print[] dict__ = header.dict1[] print[dict__] asdict__ = header.dict3[] print[asdict__] assert isinstance[dict__['message_id'], str] assert isinstance[dict__['integer'], int] assert header.dict1[] == header.dict2[] == header.dict3[] assert header_with_slots.dict[] == header_with_slots.dict2[]
dict1[]: 0.005992999998852611
dict2[]: 0.00800508284009993
dict3[]: 0.07069579092785716
slots -> dict[]: 0.00583599996753037
slots -> dict2[]: 0.07395245810039341
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
{'message_id': 'b4e17ef9-1a58-4007-9cef-39158b094da2', 'string': 'a string', 'integer': 1000, 'floating': 1.0}
1Lưu ý rằng nếu một trường được chú thích bằng loại mô tả, nhưng không được gán một đối tượng mô tả là giá trị mặc định của nó, trường sẽ hoạt động như một trường bình thường.