开发者

class with changing parameters

开发者 https://www.devze.com 2023-02-18 03:23 出处:网络
I want to define a Python class that accepts different variables as input. However I only want to declare one of them when calling the class, because the variables determine each other and in differen

I want to define a Python class that accepts different variables as input. However I only want to declare one of them when calling the class, because the variables determine each other and in different situations I have different inputs at hand. So it should be something like a class price that I call as:

foo = price(dollar=10)  
bar = price(euro=20)

and I have a function inside the class that takes the different currencies and translates them into each ot开发者_Python百科her. How do I do that?


You should use dictionary for keyword arguments. Here is how you can define it in constructor:

class Price:
    def __init__(self, **kwargs):
        if 'dollar' in kwargs and 'euro' in kwargs:
           raise Exception(..)
        if 'dollar' in kwargs:
            self.dollar = kwargs['dollar']
        elif 'euro' in kwargs:
            self.euro = kwargs['euro']
        else:
            raise Exception()
0

精彩评论

暂无评论...
验证码 换一张
取 消