开发者

class with changing parameters

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜