【问题标题】:Alternate constructor missing required positional arguments [closed]备用构造函数缺少必需的位置参数[关闭]
【发布时间】:2014-12-02 14:15:05
【问题描述】:

我编写了一个函数wczytaj 来获取所有参数,我想将它们返回给构造函数,但它不能以这种方式工作。我想知道为什么不以及如何解决它

我收到此错误:

 TypeError: wczytaj() missing 3 required positional arguments: 'a', 'b', and 'c'

不可能写一个函数,返回3个参数吗?

 from math import sqrt

 def wczytaj(a , b , c):
      a = input("Podaj parametr A? ")
      b = input("Podaj parametr B ")
      c = input("Podaj parametr C? ")
      return a , b , c

 class Rk:

      def __init__(self,a,b,c):
         self.a = a
         self.b = b        
         self.c = c


 nowe = Rk(wczytaj())


 print("Ten program rozwiązuje równanie kwadratowe po podaniu parametrów.")
 print("\n Równianie jest postaci {}x*x + {}x + {} = 0  ".format(a, b, c), end="")

【问题讨论】:

标签: python function oop


【解决方案1】:

wczytaj 函数中删除参数

def wczytaj():
      a = input("Podaj parametr A? ")
      b = input("Podaj parametr B ")
      c = input("Podaj parametr C? ")
      return a , b , c

然后您必须使用* 运算符将返回的值作为参数解压缩到您的类__init__

nowe = Rk(*wczytaj())

您现在可以看到,当我分别输入123 时,现在已经设置了成员

>>> nowe.a
1
>>> nowe.b
2
>>> nowe.c
3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2022-01-18
    • 2020-09-03
    • 2022-01-27
    • 2021-12-30
    • 2021-09-14
    相关资源
    最近更新 更多