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

2024-04-23 21:03:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我做错什么了?我对编程真的很陌生,所以我搞不懂。你知道吗


Tags: 实例self属性定义initdef字符kwargs
3条回答

您应该使用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)

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

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__之后调用该装饰器。你知道吗

相关问题 更多 >