【问题标题】:Is there a way to to make this personality quiz in object oriented programming?有没有办法在面向对象编程中进行这种个性测验?
【发布时间】:2021-11-19 11:28:27
【问题描述】:

到目前为止,我已经尝试创建将打印和计算所有类别百分比的 QBank 类,以及将输出个性类型的 PType 类。这是非面向对象的代码:

apercent = {}
apercent["A"] = 0
apercent["B"] = 0
apercent["C"] = 0
apercent["D"] = 0
questions = [
    {"q": "Would you call yourself a thinker", "f": "D"},
    {"q": "Are you creative", "f": "D"},
    {"q": "Do you like philosophy", "f": "D"},
    {"q": "Do you like to think about complex questions", "f": "D"},
    {"q": "Do you have an interest in artisitc pursuits like painting and writing", "f": "D"},
    {"q": "Do you like initiating conversations", "f": "A"},
    {"q": "Do you like to start talks with new people", "f": "A"},
    {"q": "Is it easy for you to adjust in an enviroment where you initially do not know anyone", "f": "A"},
    {"q": "Are you social", "f": "A"},
    {"q": "Do you like social events (parties, fests and events)", "f": "A"},
    {"q": "Do you mostly make your decisions by heart", "f": "B"},
    {"q": "Do you put others before yourself", "f": "B"},
    {"q": "Do you think that one should change their views if they hurt someone", "f": "B"},
    {"q": "Do you often get lost in your feelings", "f": "B"},
    {"q": "Are you run more by your feelings than logic", "f": "B"},
    {"q": "Can you make a timetable and stick to it", "f": "C"},
    {"q": "Do you usually follow the rules/laws", "f": "C"},
    {"q": "Are you organised", "f": "C"},
    {"q": "Do you plan before doing something", "f": "C"},
    {"q": "Are you ok with following orders", "f": "C"}
]
def question(index, inp, func):
    if bool(input(str(index + 1) + ". " + inp + "? Yes/No:\t").lower().strip("no. \t")):
        apercent[func] = apercent[func] + 20
try:
     for q in range(len(questions)):
          question(q, questions[q]["q"], questions[q]["f"])
except KeyboardInterrupt:
     exit(0)
print("Your extroversion percentage : ", apercent["A"], "%")
print("Your creativity percentage : ", apercent["N"], "%")
print("Your feeling percentage : ", apercent["B"], "%")
print("Your conscientious percentage : ", apercent["C"], "%")
if apercent["N"] > 50:
    sn = "N"
else:
    sn = "S"
if apercent["A"] > 50:
    ie = "E"
else:
    ie = "I"

if apercent["C"] > 50:
    jp = "J"
else:
    jp = "P"

if apercent["B"] > 50:
    tf = "F"
else:
    tf = "T"
ptype = ie + sn + tf + jp
print("Your personality type is: ", ptype)

这就是我尝试使 QBank 面向对象的方式:

class QBank:

  def _init_(self, questions, percentage):
    self.questions = questions
    self.percentage = percentage


  def printQuestions(self, q):
    q = ["Would you call yourself a thinker (Y/N):",
    "Are you creative (Y/N):",
    "Do you like philosophy (Y/N):",
    "Do you like to think about complex questions (Y/N):",
    "Do you have an interest in artisitc pursuits like painting and writing (Y/N):",
    "Do you like initiating conversations (Y/N):",
    "Do you like to start talks with new people (Y/N):",
    "Is it easy for you to adjust in an enviroment where you initially do not know anyone (Y/N):",
    "Are you social (Y/N):",
    "Do you like social events (parties, fests and events) (Y/N):",
    "Do you mostly make your decisions by heart (Y/N):",
    "Do you put others before yourself (Y/N):",
    "Do you think that one should change their views if they hurt someone (Y/N):",
    "Do you often get lost in your feelings (Y/N):",
    "Are you run more by your feelings than logic (Y/N):",
    "Can you make a timetable and stick to it (Y/N):",
    "Do you usually follow the rules/laws (Y/N):",
    "Are you organised (Y/N):",
    "Do you plan before doing something (Y/N):",
    "Are you ok with following orders (Y/N):"]

    f= ["D","D","D","D","D","A","A","A","A","A","B","B","B","B","B","C","C","C","C","C",]

    z = list(zip(q,f))

    for x in range (len(q)):
      print(q, input(" "))

print(QBank.printQuestions(q))

这是针对 PType 的

class PType:
    def __init__(self, personality, anime, movie, career):
        self.personality  = personality
        self.anime = anime
        self.movie = movie
        self.career = career

    def printValues(self):
        print("Your personality type is: ", self.personality)
        print("Anime character: ", self.anime)
        print("Tv show/movie character: ", self.movie)
        print("Career options: ", self.career)

    def calculatePtype(self):
        pass
        

p1 = PType("ENTJ", "Mikasa Ackerman", "Harrison Wells", "Businessman")

p1.printValues()

我只是真的坚持如何在面向对象的 python 编程中做到这一点。特别是对于计算。有人可以帮我吗?

【问题讨论】:

    标签: python object-oriented-analysis


    【解决方案1】:

    OOP 是一种不同的编程范式,即一种不同的代码思考方式。因此,仅仅在类定义中放置或多或少相同的过程代码不会使其成为 OOP。

    我冒昧地摸索了一下你的代码,我想出了四个类:问题、个性特征、个性类型,最后是一个测验类,它除了创建其他类的对象并调用它们的方法之外什么都不做:

    from dataclasses import dataclass
    
    @dataclass
    class Question:
        text : str
        ptrait_code : str
    
        def ask(self):
            return (self.ptrait_code, input(f'{self.text}?: Yes/No')[0].upper() == "Y")
    
    
    @dataclass
    class PTrait:
        code : str
        title : str
        positive : str
        positive_desc : str
        negative : str
        negative_desc : str
        score : int = 0
    
        def show_score(self):
            if self.score > 50:
                print(f'Your {self.title} score is {self.score} so you could be described as {self.positive_desc}')
            else:
                print(f'Your {self.title} score is {self.score} so you could be described as {self.negative_desc}')
    
        def score2ptype(self):
            if self.score > 50:
                return self.positive
            return self.negative
    
    
    @dataclass
    class PType:
        code : str
        anime : str
        movie : str
        career : str
        
        def show_result(self):
            print(f'Your personality type is {self.code}')
            print(f'Your anime character is {self.anime}')
            print(f'Your movie is {self.movie}')
            print(f'Your career is {self.career}')
    
    
    class Quiz:
        def __init__(self):
            self.questions = [Question("Would you call yourself a thinker","CRE"),
                              Question("Are you creative","CRE"),
                              Question("Do you like philosophy","CRE")
                              ]
            self.ptraits = {"EXT" : PTrait("EXT", "Extroversion", "E", "Extroverted", "I", "Introverted"),
                            "CRE" : PTrait("CRE", "Creativity", "N", "Creative", "S", "Down-to-earth")
                            }
            self.ptypes = {'ENTJ' : PType('ENTJ', "Mikasa Ackerman", "Harrison Wells", "Businessman")
                           }
            self.computed_ptype = ''
    
        def run_quiz(self):
            for q in self.questions:
                trait, answer = q.ask()
                if answer:
                    self.ptraits[trait].score += 20
            print()
            for trait in self.ptraits:
                self.ptraits[trait].show_score()
                self.computed_ptype += self.ptraits[trait].score2ptype()
            print()
            ##force ENTJ since a few data are missing
            self.computed_ptype = "ENTJ"
            self.ptypes[self.computed_ptype].show_result()
    
    q=Quiz()
    q.run_quiz()
                
    Would you call yourself a thinker?: Yes/No y
    Are you creative?: Yes/No y
    Do you like philosophy?: Yes/No y
    
    Your Extroversion score is 0 so you could be described as Introverted
    Your Creativity score is 60 so you could be described as Creative
    
    Your personality type is ENTJ
    Your anime character is Mikasa Ackerman
    Your movie is Harrison Wells
    Your career is Businessman
    

    【讨论】:

    • 非常感谢! just a q: @dataclass 只是 def init func 的快捷方式,对吗?
    • 基本上是的。但是检查文档,这很有趣
    • 你好,所以我在输入信息后尝试运行它,无论我输入什么,它都会显示输出中所有类别的 100。当你不强迫ENTJ时你会放什么?
    • def run_quiz(self): for q in self.questions: trait, answer = q.ask() if answer: self.ptraits[trait].score += 20 print() for trait in self.ptraits: self.ptraits[trait].show_score() self.computed_ptype += self.ptraits[trait].score2ptype() print() #force ENTJ for now self.computed_ptype = "ENTJ" self.ptypes[self.computed_ptype].show_result() 这是我不明白的部分
    • 对不起,我复制错了。我正在编辑input 行,以便我们获得正确的布尔值。对于第二个问题,只需删除self.computed_ptype = "ENTJ",前面的循环负责填充变量
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    相关资源
    最近更新 更多