尝试使用** kwargs来定义类中的属性

问题描述 投票:0回答:3

所以我有一个定义字符及其属性的类,它是这样的:

class character():

    def __init__(self, health, dodge, damage, critAdd):

        self.health=health
        self.dodge=dodge
        self.damage=damage
        self.critAdd=critAdd

当我创建一个实例时:

knight=character(150, 5, 40, 1.5)

它完美地运作。但我想创建的是一种用键值创建它的方法,如下所示:

knight=character(health=150, dodge=5, damage=40, critAdd=1.5)

所以我尝试使用__init__这样写**kwargs

def __init__(self, **kwargs):

    self.health=health
    self.dodge=dodge
    self.damage=damage
    self.critAdd=critAdd

它说:

NameError: name 'health' is not defined

我究竟做错了什么?我真的很喜欢编程,所以我无法弄明白。

python python-3.x kwargs
3个回答
0
投票

kwargs只是一个映射;它不会神奇地为您的函数创建局部变量。您需要使用所需的键索引python字典。

def __init__(self, **kwargs):
    self.health = kwargs['health']
    self.dodge = kwargs['dodge']
    self.damage = kwargs['damage']
    self.critAdd = kwargs['critAdd']

dataclass简化了这个:

from dataclasses import dataclass

@dataclass
class Character:
    health: int
    dodge: int
    damage: int
    critAdd: float

这会自动生成您原来的__init__

如果你需要在添加数据类装饰器后在__init__中做额外的工作,你可以定义一个数据类将在__post_init__之后调用的__init__


1
投票

您不需要使用**kwargs定义方法来支持按关键字传递参数。您的原始版本的__init__已经支持您要使用的character(health=150, dodge=5, damage=40, critAdd=1.5)语法。你的原始版本比使用**kwargs更好,因为它确保通过正确的参数,拒绝像helth=150拼写错误。


-2
投票

你应该使用get(),例如:

class Example():
    def __init__(self, **kwargs):

  self.health= kwargs.get('health', 10) # The first argument is the variable you want
                                        # The second is the default in case this kwarg do not exist


a = Example(health=50)
b = Example()

print(a.health)
print(b.health)

© www.soinside.com 2019 - 2024. All rights reserved.