Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从函数返回值作为类属性_Python_Function_Python 3.x_Parameter Passing - Fatal编程技术网

Python 从函数返回值作为类属性

Python 从函数返回值作为类属性,python,function,python-3.x,parameter-passing,Python,Function,Python 3.x,Parameter Passing,假设我有一个函数和一个这样的类 >>> def something(): ... x = 5 ... y = 6 ... return x, y >>> class SomethingElse(): ... def __init__(self, x, y): ... self.x = x ... self.y = y ... print(x+y) ...

假设我有一个函数和一个这样的类

>>> def something():
...     x = 5 
...     y = 6
...     return x, y

>>> class SomethingElse():
...     def __init__(self, x, y):
...             self.x = x
...             self.y = y
...             print(x+y)
... 
我想把函数返回的属性传递给我的类,这样做可行吗?因为当我调用我的函数时,我只得到一个属性

>>> S = SomethingElse(5, 6)
11
>>> S1 = SomethingElse(something)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'y'
您可以使用splat(或“解包”)操作符
*
,如下所示

>>> SomethingElse(*something())
11

这可以在Python教程中看到,通常称为参数解包

您有几个选择

这使得
y
成为可选参数。使用
SomethingElse(something())
SomethingElse(5,6)
调用它

这个定义了一个助手函数
make_kind
,它返回一个
SomethingElse
的新实例。您可以使用
SomethingElse.make_kind()调用它;不需要
self
参数

class SomethingElse():
     def __init__(self, x, y):
         self.x = x
         self.y = y
         print(x + y)

     @staticmethod
     def make_kind():  
          x = 5 
          y = 6
          return SomethingElse.__init__(x, y)

了解有关官方Python 3.5文档的更多信息。

我认为这根本不能解决问题。@juanpa.arrivillaga为什么不能?只是“我认为这根本不能解决问题”是没有帮助的。问题是如何将元组传递给构造函数。您的第一个选项实际上毫无意义,应该使用splat操作符来替代。您的第二个选项对设计进行了假设-它可能是一个有效的解决方案,但再次说明,并没有回答问题。我将坚持第一个答案,打开列表。@noɥzɐzɹ操作符重载?为什么呢为什么这是件好事?我很确定这是一个语法错误。像
SomethingElse(something)
这样使用它肯定是错误的,因为
something
是一个函数对象。
class SomethingElse():
     def __init__(self, x, y=None):
         if y is None:
             x, y = *x
         self.x = x
         self.y = y
         print(x + y)
class SomethingElse():
     def __init__(self, x, y):
         self.x = x
         self.y = y
         print(x + y)

     @staticmethod
     def make_kind():  
          x = 5 
          y = 6
          return SomethingElse.__init__(x, y)