【问题标题】:How to setup default arguments for class methods as class variables?如何将类方法的默认参数设置为类变量?
【发布时间】:2019-03-28 05:29:00
【问题描述】:

我想为类方法提供合理的默认参数作为类变量。这些变量应该在调用它们时传递给类方法,除非用户想要覆盖它们。我想出了下面的解决方案,但我不确定这是否有意义。它做我想做的事,但我很想知道是否有更好或更 Pythonic 的方法来做到这一点。

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

【问题讨论】:

    标签: python class keyword-argument


    【解决方案1】:

    这个怎么样

    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))
    

    【讨论】:

    • 这就是我最初想要的,但我认为这有更多冗余代码。您需要两次声明所有默认参数,当您有很多类方法和关键字参数时,这会变得有点混乱。
    猜你喜欢
    • 2011-06-25
    • 2013-02-17
    • 2018-11-22
    • 2019-03-22
    • 2013-02-22
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多