Skip to main content
 首页 » 编程设计

python之将参数传递给 Python 中的类方法的问题

2025年05月04日9wuhuacong

过去一周我一直在玩 Python,我遇到了将 4 个参数传递给类方法的问题。

这是在它的类中定义的类方法:

class Line: 
    locx0 = 0 
    locy0 = 0  
    locx1  = 0 
    locy1 = 0 
    def __init__(self): 
        print'<<Line __init__()>>' 
 
 
    def setLineCoordinates(locx0, locy0, locx1, locy1): 
       self.locx0 = locx0 
       self.locy0 = locy0 
       self.locx1  = locx1 
       self.locy1 = locy1 
 
 
 
    def getLineCoordinatesX0(): 
        return self.x0 
 
    def getLineCoordinatesY0(): 
        return self.y0   
 
    def getLineCoordinatesX1(): 
        return self.x1 
 
    def getLineCoordinatesY0(): 
        return self.y0 

这里是我调用类方法的地方:

def LineDepot(): 
    x0 = None 
    x1 = None 
    y0 = None 
    y1 = None 
    line = Line() 
    print"Please enter starting and ending coordinates " 
    print"If no value is entered, then it will be assumed that the coordinate value is zero " 
    x0 = int(input('Enter value for initial x coordiante : ')) 
    y0 = int(input('Enter value for initial y coordiante : ')) 
    x1 = int(input('Enter value for end x coordiante :')) 
    y1 = int(input('Enter value for end y coordiante :')) 
 
    line.setLineCoordinates(x0, y0, x1, y1) 

这是我在输出中遇到的错误:

Please make a selection from the following menu... 
1.Create a new Line 
2.View current lines  
3.View logs 
4.Mail line info or logs 
5.View summary of line stats 
6.Exit this program 
Menu Selection:1 
<<Line __init__()>> 
Please enter starting and ending coordinates  
If no value is entered, then it will be assumed that the coordinate value is zero  
Enter value for initial x coordiante : 1 
Enter value for initial y coordiante : 2 
Enter value for end x coordiante :3 
Enter value for end y coordiante :4 
Traceback (most recent call last): 
  File "./linear.line.py", line 107, in <module> 
    Main() 
  File "./linear.line.py", line 15, in Main 
    Menu() 
  File "./linear.line.py", line 52, in Menu 
    LineDepot() 
  File "./linear.line.py", line 32, in LineDepot 
    line.setLineCoordinates(x0, y0, x1, y1) 
TypeError: setLineCoordinates() takes exactly 4 arguments (5 given) 

我终其一生都在努力弄清楚为什么当我传递 4 个参数时,解释器是 告诉我我正在尝试通过 5。

我已经并将继续研究这个问题。

如有任何帮助,我们将不胜感激。 谢谢!!!

请您参考如下方法:

你的定义中缺少 self

当调用类方法时,python 将对象引用作为第一个函数参数

def setLineCoordinates(self,x0,y0,x1,y1) 
def getLineCoordinatesX0(self): 
...