0

I want to take more arguments depending on the data type of another argument.

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

If I give the class an img, I want the class to accept img_size as another parameter but I also want it to not accept animaton as an parameter. But if I give it animation, I want the class to not need to accept img and img_size as parameters.

The difference between img and animation is that img should be an object from an Image class, and animation should be a dictionary. So how would I vary the amount of arguments that I accept depending on what they are?

User4497
  • 71
  • 6
  • 2
    If you have them as keyword arguments, you can use as few or as many as you need for a given case. Then the init method just needs to do error handling for when incompatible keywords are set. – Tyberius Jul 01 '21 at 21:17

1 Answers1

0

This can give you some ideas:

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')
funnydman
  • 9,083
  • 4
  • 40
  • 55