提问人:Zach Reese 提问时间:11/8/2022 更新时间:11/9/2022 访问量:34
从类的实例中获取值
Get a value from instance of a class
问:
class Jokes:
def __init__(self, *joke):
self.joke_list = []
self.used_joke_list = []
self.joke = joke
if self.joke not in self.joke_list and self.joke not in self.used_joke_list:
self.add_Joke(joke)
def __str__(self):
return "{} \n {}".format(self.joke.split("...")[0], self.joke.split("...")[1])
def show_Joke(self):
if len(self.joke_list) > 0:
randjoke = rand.randint(0,len(self.joke_list) - 1)
self.cur_joke = self.joke_list[randjoke]
self.used_joke_list.append(self.cur_joke)
self.joke_list.remove(self.cur_joke)
return str(self.cur_joke)
elif len(self.joke_list) == 0:
for joke in self.used_joke_list:
self.joke_list.append(joke)
self.used_joke_list.remove(joke)
self.show_Joke()
def add_Joke(self, joke):
#joke = input("What's you joke? /n")
self.joke_list.append(joke)
joke1 = Jokes("Which bear is the most condescending? A pan-duh!")
joke2 = Jokes("We're afraid for this calendar... It's days are numbered")
joke3 = Jokes("6:30 is the best time on a clock... Hands down")
joke4 = Jokes("A detective was rushed to the ER... He accidentally poked his private eye")
joke5 = Jokes("A friend of mine collects blunt pencils... Personally, I find his hobby a bit pointless")
print(Jokes.show_Joke)
我正在尝试创建一个程序来显示一个随机的坏爸爸笑话,允许用户添加新笑话,并显示一个随机笑话
我正在使用列表来存储新的和使用过的笑话以防止重复,在此示例中,我添加了一些笑话。不过,每当我尝试将节目称为笑话方法时,我得到的只是0x000002478B02A0E0><功能Jokes.show_Joke。如果我在行末尾添加 (print(Jokes.show_joke()),我会收到有关参数的错误。我不想调用类的特定实例,我希望它是随机的。
我如何让它返回笑话,以便我可以在标签上显示它?(也使用 tkinter 作为 gui,但该部分正常)
答:
1赞
Samwise
11/9/2022
#1
看起来您对类的实例是表示单个笑话还是笑话集合感到困惑。我建议把它变成一个笑话的集合,这意味着你会创造
一个对象,并向其添加一堆笑话,而不是为每个笑话创建一个对象:Jokes
Jokes
Jokes
import random
class Jokes:
def __init__(self, *jokes):
self.new_jokes = []
self.used_jokes = set()
self.add_jokes(*jokes)
def add_jokes(self, *jokes):
self.new_jokes.extend(jokes)
random.shuffle(self.new_jokes)
def __str__(self):
return " ... ".join(self.new_jokes)
def show_joke(self):
if not self.new_jokes:
# recycle all the old jokes
self.new_jokes = list(self.used_jokes)
random.shuffle(self.new_jokes)
self.used_jokes.clear()
joke = self.new_jokes.pop()
self.used_jokes.add(joke)
return joke
jokes = Jokes(
"Which bear is the most condescending? A pan-duh!",
"We're afraid for this calendar... It's days are numbered",
"6:30 is the best time on a clock... Hands down",
"A detective was rushed to the ER... He accidentally poked his private eye",
"A friend of mine collects blunt pencils... Personally, I find his hobby a bit pointless",
)
print(jokes.show_joke())
请注意,这是一个实例方法(它作为参数,因为它知道在哪里找到 和 ),因此您可以在实例上调用它,而不是在类上调用它。show_joke
self
self.new_jokes
self.used_jokes
jokes
Jokes
评论
0赞
Zach Reese
11/9/2022
我对课程完全感到困惑,哈哈,感谢您对情况的反馈。我试图制作一个笑话对象,其中包含您提到的所有笑话。我会试一试,再次感谢你!我注意到您更改了一些内容,例如 self.used_jokes = set() 为什么要这样做而不是创建另一个空字符串?而且,如果我们随机化new_jokes列表中出现的笑话,这仍然有效吗?
评论
Jokes().show_Joke()