如何创建用户指定的对象数?

时间:2016-10-31 06:43:03

标签: python class dynamic

我刚刚开始学习类和对象并了解基础知识(创建对象,分配变量和使用函数)

我正在尝试创建To-Do-List脚本。为此,我有一个班级:

class Tasks:
    name=""
    priority=3
    duration=1.5
    due_date=3

    def __init__(self):                     #inputs all the variables
    #Defines new variable new_priority            

        self.name = input("Enter the name of ", self)
        self.priority = input("Enter its priority from 1 to 5.")

        while self.priority not in range(1, 5):
            print("Please try again.The value must be between 1 and 5 \n")
            self.priority = input("Enter its priority from 1 to 5")

        self.due_date = input("When is it due?1-Today,2- Tomorrow ")

        while self.due_date == 0:
            print("Please try again.The value must not be zero")
            self.due_date = input("When is it due?1-Today,2- Tomorrow ")

        self.new_priority=self.priority * (1/self.due_date)


    def print(self):

        print(self.name, "   ", self.duration, "   ", self.due_date, 
                                               "   ",self.priority)            

在此,每个任务都是一个对象。我遇到的问题是任务数量将根据用户的偏好而定。我们可能有1,我们可能有12.如何根据用户的意愿创建对象?

1 个答案:

答案 0 :(得分:0)

I little reorganized your code.

class Task:

    def __init__(self):
     #Defines new variable new_priority

        self.name = input("Enter the name of a task: " )
        self.priority = input("Enter its priority from 1 to 5: ")

        while int(self.priority) not in range(1, 6):
            print("Please try again.The value must be between 1 and 5\n")
            self.priority = input("Enter its priority from 1 to 5: ")

        self.due_date = input("When is it due? 1-Today, 2- Tomorrow: ")

        while int(self.due_date) not in [1, 2]:
            print("Please try again.The value must not be zero\n")
            self.due_date = input("When is it due? 1-Today, 2- Tomorrow: ")

        self.duration = 1.5

        self.new_priority = float(self.priority) * (1/float(self.due_date))

    def __str__(self):
        return self.name + "   " + str(self.duration) + "   " + str(self.due_date) + "   " + self.priority


class Tasks:
    def __init__(self):
        self.tasks_list = []

    def append(self, new_task):
        self.tasks_list.append(new_task)

    def __getitem__(self, key):
        return self.tasks_list[key]


tasks = Tasks()

while True:
    tasks.append(Task())
    print("Task created: ", tasks[-1])
    answer = input("\nDo you want to create next object [Y/N]?")
    if answer is not 'Y':
        break

我将Tasks类更改为Task,并添加了新的基本Tasks类。然后你可以在循环中询问用户任务,直到他们不想再添加。希望这会有所帮助。