如何将类方法的默认参数设置为类变量?

时间:2019-03-27 21:14:19

标签: python class kwargs

我想为类方法提供明智的默认参数作为类变量。这些变量应在调用时传递给类方法,除非用户想要覆盖它们。我想出了下面的解决方案,但是我不确定这是否有意义。它可以实现我想要的功能,但是我很想知道是否有更好或更多的Python方式可以做到这一点。

from copy import deepcopy


class Cat:
    def __init__(self):
        self.parameters = {'meow': {'volume': 10.2,
                                    'pitch': 'E'},
                           'sleep': {'duration': 100,
                                     'snore': True,
                                     'dream': True}}

    def meow(self, **kwargs):
        params = self._set_parameters('meow', kwargs)
        print('Meowing at {volume} dB in {pitch}'.format(**params))

    def sleep(self, **kwargs):
        params = self._set_parameters('sleep', kwargs)
        print('Sleeping for {duration} hours...\n'
              'Snore: {snore}\nDream: {dream}'.format(**params))

    def _set_parameters(self, action, kwargs):
        params = deepcopy(self.parameters[action])
        for key in kwargs:
            if key in params:
                params[key] = kwargs[key]
        return params

如果使用默认值,则在没有任何参数的情况下调用类方法。

Sleepycat = Cat()
Sleepycat.sleep()

>>> Sleeping for 100 hours...
    Snore: True
    Dream: True

用户还可以提供关键字参数来覆盖默认值:

Loudcat = Cat()
Loudcat.meow(volume=100)

>>> Meowing at 100 dB in E

1 个答案:

答案 0 :(得分:0)

关于

class Cat:
    def __init__(self):
         self.sleep_duration = 100
         self.sleep_snore = True
         self.sleep_dream = True

    def sleep(self, 
              duration=100, 
              snore=True, 
              dream=True):
        self.sleep_duration = duration
        self.sleep_snore = snore
        self.sleep_dream = dream

        print('Sleeping for {0} hours...\n'
              'Snore: {1}\nDream: {2}'.format(
                self.sleep_duration, self.sleep_snore, self.sleep_dream))