如何使用* args和** kwargs为行编写类?

时间:2019-11-18 01:44:02

标签: 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: 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 <时遇到了一些麻烦/ strong>与这些形式参数一起使用。这是给班级的任务,但是我没有从同龄人或我的教授那里得到太多帮助,只是想获得一些关于从这里出发的指导。非常感谢!

2 个答案:

答案 0 :(得分:0)

* args为您提供了传入参数的列表。如果您有函数function(1, 2, "stuff"),则将找到args = [1, 2, "stuff"]

** kwargs为您提供了传入的 keyword 参数的字典;就是那些有名字的人。因此,如果您传入函数function(x='foo', y='bar'),则会发现`kwargs = {x:'foo',y:'bar'}。

这是一个不错的page with more tips

答案 1 :(得分:0)

这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')

def __init__(self, *args, **kwargs):
    self.line = args[0]
    self.slope = args[1]
    self.intercept = args[2]

请注意,args希望您以“正确”的顺序传递参数,但是函数定义不会记录该顺序或以任何方式警告您。 因此,当您不需要关心函数接收参数的顺序时,最好使用* args。否则,其他方法会更安全。