簡體   English   中英

將變量作為 arguments 列表傳遞

[英]Passing a variable as a list of arguments

我的代碼如下。 在制作更多數據庫之前,我只是讓基本功能正常工作,但我遇到了一個問題 - 有沒有辦法將變量傳遞給四個不同的 arguments? 我的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)

我在這里包括了我的人 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

您可以使用 python 的內置getattr方法來訪問 object 的屬性值。 以下行應該有效:

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