简体   繁体   English

我的 object 函数做错了什么?

[英]What am I doing wrong with my object functions?

So my goal is to create a quiz.所以我的目标是创建一个测验。 I first went about it with global variables but despite using return and global indicator I couldn't get it to work so I went to classes and objects.我首先使用全局变量来解决它,但是尽管使用了返回和全局指示器,但我无法让它工作,所以我去了类和对象。 Below is a small sample with an answer to the first question.下面是一个小样本,其中包含第一个问题的答案。

print('Hello, Welcome to the what bender are you test!')
print('Answer the questions one at a time in order and in lower case. When youre done 
       answering all of them type Done to get your results. Ready? Lets go!')

print('What is your favorite rainbow color? Indigo and Violet are in here too.')
print('Do you know your blood type? Just answer yes or no ^^')
print('What is your Hogwarts House?')
print('Out of these four animals which do you prefer? Deer, Ram, Longhorn 
      Hummingbird')


class Benders():
    def __init__(self,points = 0):
    self.points = points



Firebender = Benders()
Airbenders = Benders()
Waterbenders = Benders()
Earthbenders = Benders()
    

def red():
       setattr(Firebender.Points,1)

I dont know what to do, I can't leave red in the class functions or people cant type in the answer to change the attribute.我不知道该怎么办,我不能在 class 函数中留下红色,或者人们不能输入答案来更改属性。 I've also tried putting the class in the parenthesis to clarify for python. Please help我还尝试将 class 放在括号中以澄清 python。请帮忙

setattr takes the object and the attribute name as separate arguments: setattr将 object 和属性名称作为单独的 arguments:

setattr(Firebender, 'points', 1)

but it's simpler to just write但是写起来更简单

Firebender.points = 1

setattr is more useful when the name of the attribute you want to change is stored in a variable, and so you can't use the dot notation:当您要更改的属性的名称存储在变量中时, setattr更有用,因此您不能使用点表示法:

attribute = "points"
# Firebender.attribute = 1  # sets attribute, not points
setattr(Firebender, attribute, 1)  # OK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM