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

时间:2019-02-27 19:59:23

标签: python python-3.x kwargs

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

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

我在做什么错?我真的是编程新手,所以我无法弄清楚。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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__之后调用。

答案 2 :(得分:-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)