简体   繁体   English

Python对象.__ new __()在main()中不接受任何参数

[英]Python object.__new__() takes no parameters in main()

I try to execute some python code but i face a problem with passing the parameters. 我尝试执行一些python代码,但在传递参数时遇到问题。 My python code is the following: 我的python代码如下:

#!/usr/bin/python
import MySQLdb

class Sim(object):

    def print_db_parameters(self):
         print "Host = %s" %self.host
         print "User = %s" %self.user
         print "Password = %s" %self.password
         print "Database = %s" %self.database

def main():
    host = "localhost"
    user = "root"
    password = "root"
    database = "sim"
    sim_test = Sim(host,user,password,database)
    sim_test.print_db_parameters()

if __name__ == "__main__":
    main()   

When i run it, i receive the following error: 当我运行它时,我收到以下错误:

Traceback (most recent call last):
  File "Sim.py", line 21, in <module>
    main()   
  File "Sim.py", line 17, in main
    sim_test = Sim(host,user,password,database)
  TypeError: object.__new__() takes no parameters

Do you have any idea? 你有什么主意吗?

You don't have an __init__ method for your class, but you're passing parameters to the constructor. 您的类没有__init__方法,但是您正在将参数传递给构造函数。 You should create an __init__ method that accepts parameters. 您应该创建一个接受参数的__init__方法。

You are passing parameters to a class constructor 您正在将参数传递给类构造函数

sim_test = Sim(host,user,password,database)

But not accepting them. 但不接受他们。 You must create an __init__ method to deal with them. 您必须创建__init__方法来处理它们。

#!/usr/bin/python
import MySQLdb

class Sim(object):
    def __init__(self, host, user, password, database):  #New method!!
        self.host = host
        self.user = user
        self.password = password
        self.database = database

    def print_db_parameters(self):
         print "Host = %s" %self.host
         print "User = %s" %self.user
         print "Password = %s" %self.password
         print "Database = %s" %self.database

def main():
    host = "localhost"
    user = "root"
    password = "root"
    database = "ARISTEIA_vax"
    sim_test = Sim(host,user,password,database)
    sim_test.print_db_parameters()

if __name__ == "__main__":
    main()   

to follow up mipadi with example: It would probably be very helpful to read some tutorials on object oriented programming in python http://docs.python.org/2/tutorial/classes.html 用示例跟进mipadi:阅读一些有关python http://docs.python.org/2/tutorial/classes.html中面向对象编程的教程可能会非常有帮助。

class Sim(object):

    def __init__(self, host, user, password, database):
       self.host = host
       self.user = user
       self.password = password
       self.database = database

    def print_db_parameters(self):
         print "Host = %s" %self.host
         print "User = %s" %self.user
         print "Password = %s" %self.password
         print "Database = %s" %self.database

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM