假设有个类,其初始化函数如下
class Foo:
def __init__(self, name, age, gender, family, score, ...):
self.name = name
self.age = age
self.gender = gender
...
总之就是把参数列表里面所有的 args 和 kwargs 里的参数都变成类的属性变量。请问有什么简洁的办法吗?这样一个一个赋值太麻烦了。
1
ericls 2020-02-06 00:35:37 +08:00 via iPhone
**kwargs 或者直接传个 dict 或者别的什么 iterable
|
2
watsy0007 2020-02-06 00:51:14 +08:00 2
data_classes
|
3
pengdirect 2020-02-06 01:02:36 +08:00 via iPhone
*arg
|
4
ipwx 2020-02-06 01:37:23 +08:00 via Android
优先选择 dataclass。不能用,就用 **kwargs, setattr
|
5
imn1 2020-02-06 02:10:55 +08:00
dataclass
|
6
676529483 2020-02-06 09:29:26 +08:00
虽然**kwargs 可以解决问题,但不觉得参数太多,应该抽象成单独的类传进去吗?
|
7
ClericPy 2020-02-06 09:31:28 +08:00 7
四种, https://paste.ubuntu.com/p/fMRyDqJPRY/
```python # 1. use dataclass at python3.7+, recommended from dataclasses import dataclass @dataclass class 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 站貌似对代码支持的一塌糊涂 |
8
PTLin 2020-02-06 09:32:19 +08:00
class Foo:
def __init__(self, name, age): self.__dict__.update(locals()) |
9
janxin 2020-02-06 09:41:20 +08:00
dataclass for 3.7+
attrs for 2.x/3.7- |
10
mathzhaoliang OP 我现在这个代码要兼容 python3.5 python3.6
dataclass 看来用不了了 |
11
watsy0007 2020-02-07 10:41:22 +08:00
@mathzhaoliang 用不了用 NamedTuple
|