【问题标题】:Python: How to override data attributes in method calls?Python:如何在方法调用中覆盖数据属性?
【发布时间】:2010-07-25 20:27:24
【问题描述】:

我的问题是如何在方法中使用数据属性,但在调用方法时允许它们被单独覆盖。这个例子展示了我是如何做到的:

class Class:
    def __init__(self):
         self.red = 1
         self.blue = 2
         self.yellow = 3
    def calculate(self, red=self.red, blue=self.blue, yellow=self.yellow):
         return red + blue + yellow

C = Class
print C.calculate()
print C.calculate(red=4)

我想要完成的工作有意义吗?当调用计算函数时,我希望它默认使用红色、蓝色和黄色的数据属性。但是,如果方法调用明确指定了不同的参数(red=4),我希望它改用该指定值。当我运行它时,它给出了使用“自我”的错误。在参数字段中(说它没有定义)。有没有办法使这项工作?谢谢。

【问题讨论】:

    标签: python attributes methods


    【解决方案1】:

    你不能参考self,因为它还没有在范围内。

    惯用的方法是这样做:

    def calculate(self, red=None, blue=None, yellow=None):
        if red is None:
            red = self.red
        if blue is None:
            blue = self.blue
        if yellow is None:
            yellow = self.yellow
        return red + blue + yellow
    

    “地道”,唉,并不总是意味着“漂亮、简洁和 Pythonic”。

    编辑:这并没有让它变得更好,是吗...

    def calculate(self, red=None, blue=None, yellow=None):
        red, blue, yellow = map(
            lambda (a, m): m if a is None else a,
            zip([red, blue, yellow], [self.red, self.blue, self.yellow]))
        return red + blue + yellow
    

    【讨论】:

    • 如您所说,并不像人们希望的那样简洁——但肯定是有用的。非常感谢!
    【解决方案2】:

    另一种选择是使用 **kwargs 和类属性:

    class Calc:
      defaults = {
          'red': 1, 'blue': 2, 'yellow': 3
          }
      def __init__(self, **kwargs):
        self.__dict__.update(self.defaults)
        self.__dict__.update(kwargs)
    

    【讨论】:

      【解决方案3】:

      你可以用更少的行来写:

      def calculate(self, red=None, blue=None, yellow=None):
          red = self.red if red is None else red
          blue = self.blue if blue is None else blue
          yellow = self.yellow if yellow is None else yellow
          return red + blue + yellow
      

      【讨论】:

      • 如果颜色可以为 0(很可能),则第一种方法失败。第二个没问题。
      猜你喜欢
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2019-07-25
      • 1970-01-01
      • 2011-07-06
      相关资源
      最近更新 更多