简体   繁体   English

将变量作为 arguments 列表传递

[英]Passing a variable as a list of arguments

My code is below.我的代码如下。 I'm just getting the basic functionality working before making more of the database, but I've run into a problem - Is there any way to pass a variable into four different arguments?在制作更多数据库之前,我只是让基本功能正常工作,但我遇到了一个问题 - 有没有办法将变量传递给四个不同的 arguments? My create_person function uses four arguments, but I need to initiate this after I create a Person object.我的create_person function 使用了四个 arguments,但我需要在创建Person object 后启动它。

import os
import sqlite3
from personClass import *

#Connection to database - ToDoDB.db
conn = sqlite3.connect('ToDoDB.db')

cursor = conn.cursor()

def create_table_ToDo():
    cursor.execute("""CREATE TABLE ToDo (
                    Forename text,
                    Surname text, 
                    FirstChore text,
                    SecondChore text
                      )""")
    print("ToDo table successfuly created!")
    conn.commit()


def create_person(Forename, Surname, FirstChore, SecondChore):
    query= "INSERT INTO ToDo (Forename, Surname, FirstChore, SecondChore)values (?,?,?,?);" #Inserts values below into this - question mark to sanitize first -
    cursor.execute(query,(Forename, Surname, FirstChore, SecondChore)) #- then executes this command
    conn.commit()       #Commit and close after each function to save
    print("New person and tasks added to the list of users")



#create_table_ToDo()

johnTest = Person("John", "Test", "Ironing clothes", "Washing dishes")
print(johnTest)

create_person(johnTest)

I've included my person class here just in case it helps.我在这里包括了我的人 class 以防万一。

class Person(ToDo):
    def __init__(self, firstName, lastName, choreOne, choreTwo):
        super().__init__(choreOne, choreTwo)
        self.firstName = firstName
        self.lastName = lastName
     
    def getName(self):
     print("My name is " + self.firstName + " " + self.lastName)

    def getTasks(self):
        print("My name's " + self.firstName + " and my tasks are " + self.choreOne + ", " + self.choreTwo)

    def __repr__(self):
        response = "{},{},{},{}".format(
            self.firstName,
            self.lastName,
            self.choreOne,
            self.choreTwo)
        return response

You can use python's built-in getattr method to access the attribute values of an object.您可以使用 python 的内置getattr方法来访问 object 的属性值。 The following line should work:以下行应该有效:

create_person(getattr(johnTest, 'firstName'), getattr(johnTest, 'lastName'), getattr(johnTest, 'choreOne'), getattr(johnTest, 'choreTwo'))

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

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