0

我尝试执行一些 python 代码,但我在传递参数时遇到了问题。我的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()   

当我运行它时,我收到以下错误:

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

你有什么主意吗?

4

3 回答 3

3

您的类没有__init__方法,但您将参数传递给构造函数。您应该创建一个__init__接受参数的方法。

于 2012-11-28T19:17:58.750 回答
3

您正在将参数传递给类构造函数

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

但不接受他们。您必须创建一种__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()   
于 2012-11-28T19:22:12.500 回答
1

以示例跟进 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
于 2012-11-28T19:22:07.823 回答