Skip to main content
 首页 » 编程设计

python之使用 Python 构造函数时出错

2025年05月04日7myhome

class fileDetails : 
 
    def __init__(self,host,usr,pwd,database): 
        self.host=host 
        self.usr.usr 
        self.pwd=pwd 
        self.database=database 
 
    def __init__(self,connection,sql,path): 
        self.connection=mysql_connection() 
        self.sql=sql 
        self.path=path 

如果我使用构造函数然后它给出一个错误:

onnetction = fileDetails('localhost',"root","",'bulsorbit') 
TypeError: __init__() takes exactly 4 arguments (5 given) 

请您参考如下方法:

构造函数(或任何其他函数)的重载在 python 中是不允许的。所以你不能为你的类定义两个 __init__ 函数。

你可以看看this post或 this one

主要思想是使用默认值或创建“备用构造函数”或检查参数的数量和类型,以便选择要使用的方法申请。

def __init__(self, **args): 

那么 args 将是一个包含所有参数的字典。所以你将能够做出不同

connection = fileDetails(host='localhost',usr="root",pwd="",database='bulsorbit') 

和

connection = fileDetails(connection="...",sql="...",path="...")