Skip to main content
 首页 » 编程设计

python之元组作为类中的返回值和参数

2025年05月04日15落叶无声

所以我有一个 Point 类,它基本上由 X 和 Y 坐标组成,我想创建一个 Rectangle 类,它是从其左上角的一个点构造的角、宽度和高度。

我的想法是将 Point 对象作为参数传递,这样 Rectangle 类构造函数将使用参数的 x 和 y 值,它们应该作为元组返回并分配给新对象,但它不起作用。

这是我的代码:

class Point: 
    def __init__(self, init_x, init_y): 
        self.x = init_x 
        self.y = init_y 
 
    def get_point(self): 
        return(self.x, self.y) 
 
class Rectangle: 
    def __init__(self,point,height,width): 
        self.top_left = Point(point.get_point()) 
 
my_point = Point(1,2) 
my_rectangle = Rectangle(my_point,2,2) 
print(my_rectangle.top_left) 

这是错误信息:

Traceback (most recent call last): 
  File "/Users/mac/Desktop/programming/python/rectangle.py", line 70, in <module> 
    my_rectangle = Rectangle(my_point,2,2) 
  File "/Users/mac/Desktop/programming/python/rectangle.py", line 67, in __init__ 
    self.top_left = Point(point.get_point()) 
TypeError: __init__() missing 1 required positional argument: 'init_y' 

为什么不将这两个值作为元组传递?有没有办法做我想做的事?

请您参考如下方法:

您需要使用* 解包语法来解包元组:

self.top_left = Point(*point.get_point()) 

否则,get_point 返回的元组将被视为只有一个参数:

>>> def func(a, b): 
...     return a, b 
... 
>>> func((1, 2)) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: func() missing 1 required positional argument: 'b' 
>>> func(*(1, 2)) 
(1, 2) 
>>>