Python 怎么初始化一个参数很多的类来着

2020-02-06 00:01:14 +08:00
 mathzhaoliang

假设有个类,其初始化函数如下

class Foo:
    def __init__(self, name, age, gender, family, score, ...):
        self.name = name
        self.age = age
        self.gender = gender
        ...

总之就是把参数列表里面所有的 args 和 kwargs 里的参数都变成类的属性变量。请问有什么简洁的办法吗?这样一个一个赋值太麻烦了。

4326 次点击
所在节点    Python
11 条回复
ericls
2020-02-06 00:35:37 +08:00
**kwargs 或者直接传个 dict 或者别的什么 iterable
watsy0007
2020-02-06 00:51:14 +08:00
data_classes
pengdirect
2020-02-06 01:02:36 +08:00
*arg
ipwx
2020-02-06 01:37:23 +08:00
优先选择 dataclass。不能用,就用 **kwargs, setattr
imn1
2020-02-06 02:10:55 +08:00
dataclass
676529483
2020-02-06 09:29:26 +08:00
虽然**kwargs 可以解决问题,但不觉得参数太多,应该抽象成单独的类传进去吗?
ClericPy
2020-02-06 09:31:28 +08:00
四种, 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 站貌似对代码支持的一塌糊涂
PTLin
2020-02-06 09:32:19 +08:00
class Foo:
def __init__(self, name, age):
self.__dict__.update(locals())
janxin
2020-02-06 09:41:20 +08:00
dataclass for 3.7+
attrs for 2.x/3.7-
mathzhaoliang
2020-02-06 14:54:28 +08:00
我现在这个代码要兼容 python3.5 python3.6
dataclass 看来用不了了
watsy0007
2020-02-07 10:41:22 +08:00
@mathzhaoliang 用不了用 NamedTuple

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/642417

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX