Python 如何使用*args和**kwargs为行编写类?
这是我的代码,其中“#TODO”是我现在一直坚持的部分:Python 如何使用*args和**kwargs为行编写类?,python,Python,这是我的代码,其中“#TODO”是我现在一直坚持的部分: import matplotlib.pyplot as plt import numpy as np abscissa = np.arange(20) plt.gca().set_prop_cycle('color', ['red', 'green', 'blue', 'black']) class MyLine: def __init__(self, *args, **kwargs): #TODO: Impl
import matplotlib.pyplot as plt
import numpy as np
abscissa = np.arange(20)
plt.gca().set_prop_cycle('color', ['red', 'green', 'blue', 'black'])
class MyLine:
def __init__(self, *args, **kwargs):
#TODO: Implement function
def draw(self):
plt.plot(abscissa,self.line(abscissa))
def get_line(self):
return "y = {0:.2f}x + {1:.2f}".format(self.slope, self.intercept)
def __str__(self):
return self.get_line()
def __mul__(self,other):
#TODO: Implement function
if __name__ == "__main__":
x1 = MyLine((0,0), (5,5),options = "2pts")
x1.draw()
x2 = MyLine((5,0),-1/4, options = "point-slope")
x2.draw()
x3 = MyLine("(-4/5)*x + 5", options = "lambda")
x3.draw()
x4 = MyLine("x + 2", options = "lambda")
x4.draw()
print("The intersection of {0} and {1} is {2}".format(x1,x2,x1*x2))
print("The intersection of {0} and {1} is {2}".format(x1,x3,x1*x3))
print("The intersection of {0} and {1} is {2}".format(x1,x4,x1*x4))
plt.legend([x1.get_line(), x2.get_line(), x3.get_line(), x4.get_line()], loc='upper
left')
plt.show()
至少,该类应该有三个实例变量(slope、intercept和line=lambda x:f(x)),但我在弄清楚如何使用这些形式参数实现init函数时遇到了一些问题。这是一个课堂作业,但我没有从同学或我的教授那里得到太多帮助,只是想从这里得到一些指导。非常感谢你 *args提供传入的参数列表。如果您有一个函数
function(1,2,“stuff”)
,您将发现args=[1,2,“stuff”]
**kwargs为您提供了传入的关键字参数的字典;就是那些有名字的。因此,如果您传入一个函数函数(x='foo',y='bar')
,您将发现'kwargs={x'foo',y'bar'}
这是一个很好的例子。这3个参数中哪一个是必需的*args(参数值列表)和**kwargs(参数名称和值对字典)参数通常表示可选参数 如果所有参数都是强制性的,我建议以正常方式实施:
def __init__(self, line, slope, intercept):
self.line = line
self.slope = slope
self.intercept = intercept
如果必须使用*args和**kwargs,可以按以下方式执行
def __init__(self, *args, **kwargs):
self.line = kwargs.get('line')
self.slope = kwargs.get('slope')
self.intercept = kwargs.get('intercept')
或
请注意,args希望您以“正确”的顺序传递参数,但函数定义不会记录该顺序或以任何方式警告您。
因此,当您不需要关心函数接收参数的顺序时,最好使用*args。否则,其他方法更安全。我觉得*args部分很有意义。我只是很难弄清楚我假设是**kwargs的输入的选项=“(…)”,是如何转换为编写这个init函数的。对。然后在init中,如果您执行
打印(kwargs)
,您将看到{'option':
def __init__(self, *args, **kwargs):
self.line = args[0]
self.slope = args[1]
self.intercept = args[2]