【问题标题】:How do you accept and reduce arguments depending on another argument [duplicate]您如何根据另一个论点接受和减少论点[重复]
【发布时间】:2021-09-13 22:04:09
【问题描述】:

我想根据另一个参数的数据类型获取更多参数。

class Enemy:
    def __init__(self, img, img_size, animation)
         ???

如果我给类一个img,我希望类接受img_size 作为另一个参数,但我也希望它不接受animaton 作为一个参数。但如果我给它animation,我希望类不需要接受imgimg_size 作为参数。

imganimation 之间的区别在于img 应该是来自Image 类的对象,而animation 应该是字典。那么,我将如何根据它们是什么来改变我接受的参数数量呢?

【问题讨论】:

  • 如果您将它们作为关键字参数,您可以根据给定案例的需要使用尽可能少或尽可能多的参数。那么init方法只需要在设置不兼容的关键字时进行错误处理。

标签: python-3.x


【解决方案1】:

这可以给你一些想法:

class Enemy:
    def __init__(self, img=None, *args, **kwargs):
        if img is not None:
            if 'animaton' in kwargs:
                raise Exception('animation is not allowed')
            self.img_size = kwargs['img_size']
        elif 'animation' in kwargs:
            if 'img' in kwargs or 'img_size' in kwargs:
                raise Exception('img and img_size is not allowed with animation param')


e = Enemy(animation='some', img_size='ada')

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2011-02-14
    • 2014-08-06
    • 2011-03-08
    相关资源
    最近更新 更多