Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

python - How to update a List with new Objects in a Class

I'm trying to create a telegram bot with Python that sends a new word every day. I already have the schedule function setup. As for the words - I created a class terms and I'm using the pop() method to choose the last word from the list of objects in the class. However, I still haven't been able to automatically update the object list when I add a new term to the object class.

Here's the code I have so far:

def dailyword():
class terms:
    def __init__(self, word, meaning, example):
        self.word = word
        self.meaning = meaning
        self.example = example

Munchkin = terms("Munchkin", 'a word of endearment used by parents with their children','Munchkin, eat your vegetables to grow strong')
Babe = terms("Babe",'a word of endearment that couples use','Babe, do you want to go surfing this weekend?')
Sweetie = terms("Sweetie", 'a word used between couples to show affection',"Sweetie, can you take out the trash?")

objectList = [Munchkin, Babe, Sweetie]
for x in objectList:
    popObject = (objectList.pop()) 

newdict = {'word':popObject.word,'meaning':popObject.meaning,'example':popObject.example}

wordoftheday = "BuzzWord of the day is -{word}
Meaning -{meaning}
Example -{example}".format(**newdict)

telegram_bot_sendtext(wordoftheday)
question from:https://stackoverflow.com/questions/66050864/how-to-update-a-list-with-new-objects-in-a-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The program sends the same word every time because you iterate on list and keep popping items which means the final popObject is always objectList[0]

You do not need to loop on the list. Just use objectList.pop() once.

Something like below:

def add_word(word, meaning, example):
    new_word = terms(word, meaning, example)
    objectList.append(new_word)


def send_word(objectList):
    popObject = objectList.pop()
    newdict = {'word':popObject.word,'meaning':popObject.meaning,'example':popObject.example}

    wordoftheday = "BuzzWord of the day is -{word}
Meaning -{meaning}
Example -{example}".format(**newdict)

    telegram_bot_sendtext(wordoftheday)

Hope you are enlightened!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...