raj*_*esh 1 python constructor
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
Run Code Online (Sandbox Code Playgroud)
如果我使用构造函数,那么它会给出一个错误:
onnetction = fileDetails('localhost',"root","",'bulsorbit')
TypeError: __init__() takes exactly 4 arguments (5 given)
Run Code Online (Sandbox Code Playgroud)
Thi*_*hib 10
python中不允许重载构造函数(或任何其他函数).因此,您无法__init__为您的班级定义两个函数.
主要思想是使用默认值或创建"备用构造函数" 或检查args的数量和类型,以便选择要应用的方法.
def __init__(self, **args):
Run Code Online (Sandbox Code Playgroud)
然后args将是包含所有参数的字典.所以你将能够有所作为
connection = fileDetails(host='localhost',usr="root",pwd="",database='bulsorbit')
Run Code Online (Sandbox Code Playgroud)
和
connection = fileDetails(connection="...",sql="...",path="...")
Run Code Online (Sandbox Code Playgroud)