Python: how to override data attributes in method calls?

My question is how to use data attributes in a method, but letting them override individually when the method is called. This example demonstrates how I tried to do this:

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)

Does what I'm trying to accomplish make sense? When the calculation function is called, I want it to use the data attributes for red, blue, and yellow by default. But if the method call explicitly sets a different parameter (red = 4), I want it to use that specified value. When I run this, it gives an error for using "I". in the parameter field (saying that it is not defined). Is there any way to make this work? Thank.

+3
3

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

"", , ", ".

: , ...

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
+4

- ** kwargs class:

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

You can write it in smaller lines:

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
source

Source: https://habr.com/ru/post/1756466/


All Articles