gpt4 book ai didi

Python:如何覆盖方法调用中的数据属性?

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:44 25 4
gpt4 key购买 nike

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

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”的错误。在参数字段中(说它未定义)。有没有办法使这项工作?谢谢。

最佳答案

您不能引用 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

关于Python:如何覆盖方法调用中的数据属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3330874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com