python - 如何通过遍历 __init__ 参数来创建实例属性?

标签 python class constructor args keyword-argument

我想知道是否有一种方法可以通过循环 init 方法的参数来生成类属性,而无需显式引用包含 init 方法的所有参数的列表> 方法?

在下面的示例中,我可以循环 hp、image、speed、x、y 来创建 self 参数吗?

class Character(pygame.sprite.Sprite):
    def __init__(self, hp, image, speed, x, y):

        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()

        self.image = image
        self.rect = self.image.get_rect().move(x, y) #initial placement
        self.speed = speed
        self.hp = hp

例如,循环如下所示:

class Character(pygame.sprite.Sprite):
    def __init__(self, hp, image, speed, x, y):

        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()

        for arg in arguments:
             self.arg = arg

我不太确定如何获取“参数”来引用 hp、图像、速度、x 和 y?或者我是否坚持使用如下列表?

class Character(pygame.sprite.Sprite):
    def __init__(self, hp, image, speed, x, y):

        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()

        for arg in [self, hp, image, speed, x, y]:
             self.arg = arg

最佳答案

您可以使用keyword arguments (kwargs)并定义您的实例所需的属性列表,因此您期望在 __init__() 中使用这些属性。然后你可以循环它们并通过 setattr 分配你的属性:

class Character(pygame.sprite.Sprite):
    ATTRS = ('hp', 'image', 'speed', 'x', 'y')

    def __init__(self, **kwargs):
        # Call the parent class (Sprite) constructor
        super(Character, self).__init__()
        for attr in self.ATTRS:
            setattr(self, attr, kwargs.get(attr))  # sets to None if missing
        set_rect(...)  # do your processing of x, y

或者,更简单,只需将所有 kwargs 转换为实例属性:

class Character(pygame.sprite.Sprite):
    def __init__(self, **kwargs):
        super(Character, self).__init__()
        for key, value in kwargs.items():
            setattr(self, key, value)

但是,我建议您不要这样做。它可能会使您的 __init__ 更短,但以后会损害您的工作效率,因为大多数 IDE(Eclipse-PyDev、PyCharm 等)代码完成/解析功能不会检测现有实例上的此类动态设置属性并且在调用构造函数时也不建议所需的参数,这对于使用您的类的其他编码人员来说尤其烦人。

它也不会使您的代码更具可读性。想象一下继承一个使用大量此类结构的代码库。您将学会喜欢干净的明确版本,就像您在问题中建议的第一个版本一样。缩短构造函数的折衷方案是使用 multiple assignment

self.image, self.speed, self.hp = image, speed, hp
self.rect = self.image.get_rect().move(x, y)

关于python - 如何通过遍历 __init__ 参数来创建实例属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934888/

相关文章:

python - 将 Celery 与 SQLAlchemy 和 Pyramid 结合使用

python 为什么对象属性会相互泄漏

c# - 'namespace' 但像 'type' 一样使用

javascript - 通过 SerialPort 使用 Node.js 发送字节 (0xFF)

python - 在class1内调用class2时出现AttributeError,class1没有__init__属性

python - Tensorflow:如何将张量提供给经过训练的神经网络?

C++ 函数重载和 initializer_list 构造函数

Xcode 基础 : Declare custom class with integer properties and use it in another class

java - 在构造函数中设置静态最终变量

c++ - 重载运算符的意外行为 "<<"c++