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)
我想要完成的事情有意义吗?当调用计算函数时,我希望它默认使用红色、蓝色和黄色的数据属性。但是,如果方法调用显式指定不同的参数(红色=4),我希望它改用该指定的值。当我运行此命令时,它会因使用“self”而出现错误。在参数字段中(说它没有定义)。有办法让这项工作发挥作用吗?谢谢。
My question is how to use data attributes in a method but allow them to be overridden individually when calling the method. This example demonstrates how I tried to do it:
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 it makes sense what I am trying to accomplish? When the calculate function is called, I want it to use the data attributes for red, blue, and yellow by default. But if the method call explicitly specifies a different parameter (red=4), I want it to use that specified value instead. When I run this, it gives an error for using 'self.' in the parameters field (saying it's not defined). Is there a way to make this work? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法引用
self
,因为它还不在该范围内。惯用的方法是这样做:
唉,“惯用”并不总是意味着“漂亮、简洁和Pythonic”。
编辑:这并没有让它变得更好,是吗......
You cannot refer to
self
since it's not in scope there yet.The idiomatic way is to do this instead:
"Idiomatic", alas, doesn't always mean "nice, concise and Pythonic".
Edit: this doesn't make it any better, does it...
另一种选择是使用 **kwargs 和类属性:
Another option would be to use **kwargs and a class attribute:
你可以用更少的行来写它:
You can write it in less lines: