__init __()缺少1个必要的位置参数'地址'

时间:2017-12-08 12:44:00

标签: python python-3.x

这是我的代码。我有这个错误消息: TypeError: init ()缺少1个必需的位置参数:'地址' 您认为这似乎是什么问题?

Sleep

2 个答案:

答案 0 :(得分:0)

您的__init__被宣布为nameaddress

def __init__(self, name, address):

这意味着您需要同时提供它们,因此以下内容无效:

p = Person('Swaroop')

如果您的用例无法提供地址,则可以将参数设为可选:

def __init__(self, name, address=None):

如果未提供参数,上述语句将为address提供默认值None

仔细查看您的代码,您似乎想要提供一个名称和一个地址作为两个单独的对象:

p = Person('Swaroop') # name
q = Person('Duisburg') # address

请注意,参数是按位置标识的,因此在q上,Duisburg将对应name参数。

只需使用一个对象即可实现您的目标:

p = Person('Swaroop', 'Duisburg')
p.say_name()
p.say_address()

答案 1 :(得分:-1)

import sqlite3
from sqlite3 import Error

def create_connection(db_file):
    """ create a database connection to a SQLite database """
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)   
        conn.close()

class Person(object): 
    def __init__(self, name): 
        self.name = name  

    def getName(self): 
        return self.name 

class Employee(Person): 
    def __init__(self, name, age): 
        Person.__init__(self, name) 
        self.age = age 

    def getAge(self): 
        return self.age 

class main(Employee): 

    def __init__(self, name, age, address): 
        Employee.__init__(self, name, age) 
        self.address = address 

    def display(self):
        print(self.name, self.age, self.address)

    def getAddress(self): 
        return self.address 

    def view_all_empdata(conn): 
        cur = conn.cursor()
        cur.execute("SELECT * FROM empdata")
        rows = cur.fetchall()
        for row in rows:
            print(row)

    def main():
        database = "/home/vandana/Desktop/PythonDatabase/Emp2"
        conn = create_connection(database)
        with conn:
            print("View All Employee")
            select_all_emp(conn)

if __name__ == '__main__':
    main()