Python:如何在方法调用中覆盖数据属性?
我的问题是如何在一个方法中使用数据属性,但又允许在调用这个方法时单独覆盖这些属性。这个例子展示了我尝试的方式:
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),我希望它使用这个指定的值。运行这个代码时,它在参数字段中使用'self.'时出现了错误(说这个未定义)。有没有办法让这个工作?谢谢。
3 个回答
0
你可以用更少的代码行来写这个:
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
1
另一个选择是使用 **kwargs 和类属性:
class Calc:
defaults = {
'red': 1, 'blue': 2, 'yellow': 3
}
def __init__(self, **kwargs):
self.__dict__.update(self.defaults)
self.__dict__.update(kwargs)
4
你不能在那儿使用 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
不过,“常见做法”并不总是意味着“好、简洁和符合Python风格”。
补充:这样做也没什么好处,对吧...
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