python - 是否可以直接将对象字段初始化为 __init__ 关键字参数?

标签 python class

当我写一个类时,我经常这样做:

class Bulbasaur:
  """Quite obviously, the best pokemon"""
  self __init__(self, n_potions = 0, berries = 0, nickname = '')
    self.n_potions = n_potions
    self.berries = berries
    self.nickname = nickname

也许还有其他方法可以处理以下问题 - 如果是这样,请 提供(!) - 但这样做似乎更简单:

class Bulbasaur:
  """Quite obviously, the best pokemon"""
  self __init__(self, self.n_potions = 0, self.berries = 0, self.nickname = '')
    pass

字段将直接使用来自 __init__ 参数。 这可能吗?如果不是,它的设计缺陷是什么?如果没有的话有没有 有更好的方法来处理上述场景吗?

最佳答案

这是 Python 中有意设计的决定:没有特殊的语法来定义实例应具有的属性或在创建后初始化对象。 __init__ 只是另一种方法,尽管是在实例化类的过程中调用的。

Python 3.7 中引入的数据类提供了一种减少一些样板文件的方法。类语句主体中的带注释的变量用于定义 __init__ (以及其他特殊方法)的默认实现,该实现执行您通常想要的操作,即根据 的参数设置属性>__init__:

from dataclasses import dataclass


@dataclass
class Bulbasaur:
    n_potions: int = 0
    berries: int = 0
    nickname: str = ''


b1 = Bulbasaur()
assert b1.n_potions == 0 and b1.berries == 0 and b1.nickname == ''
b2 = Bulbasaur(3, 2, 'foo')
assert b2.n_potions == 3 and b2.berries == 2 and b2.nickname == 'foo'

关于python - 是否可以直接将对象字段初始化为 __init__ 关键字参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56188784/

相关文章:

python - 将 PyTest 与 hug 和 base_url 结合使用

java - getClassHierarchy() 方法

matlab - 我在初始化 MATLAB 类时遇到问题

python - 背包约束python

c++ - 这可能会出什么问题?

c++ - 是否可以在 C++ 类声明中模板化类名?

php - 如何销毁 PHP 中的类对象?

python - 64 位处理器与 32 位操作系统程序兼容性?

python - 映射一系列 warc.gz 文件,EMR

python - 将多列和多行组合为字典中的单个值