四种,
https://paste.ubuntu.com/p/fMRyDqJPRY/```python
# 1. use dataclass at python3.7+, recommended
from dataclasses import dataclass
@
dataclassclass Data(object):
a: int
b: int
c: int
d: int
data = Data(1, 2, 3, 4)
print(data)
# Data(a=1, b=2, c=3, d=4)
print(data.a, data.b, data.c, data.d)
# 1 2 3 4
# 2. Use namedtuple
from typing import NamedTuple
class Data(NamedTuple):
a: int
b: int
c: int
d: int
data = Data(1, 2, 3, 4)
print(data)
# Data(a=1, b=2, c=3, d=4)
print(data.a, data.b, data.c, data.d)
# 1 2 3 4
# 3. Use __dict__ without __slots__
class Data(object):
def __init__(self, **kwargs):
super().__init__()
self.__dict__.update(kwargs)
data = Data(a=1, b=2, c=3, d=4)
print(data.a, data.b, data.c, data.d)
# 1 2 3 4
# 4. Use setattr with __slots__
class Data(object):
__slots__ = ('a', 'b', 'c', 'd')
def __init__(self, **kwargs):
super().__init__()
for k, v in kwargs.items():
setattr(self, k, v)
data = Data(a=1, b=2, c=3, d=4)
print(data.a, data.b, data.c, data.d)
# 1 2 3 4
```
作为一个程序员论坛, V 站貌似对代码支持的一塌糊涂