繁体   English   中英

我的 object 函数做错了什么?

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

所以我的目标是创建一个测验。 我首先使用全局变量来解决它,但是尽管使用了返回和全局指示器,但我无法让它工作,所以我去了类和对象。 下面是一个小样本,其中包含第一个问题的答案。

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)

我不知道该怎么办,我不能在 class 函数中留下红色,或者人们不能输入答案来更改属性。 我还尝试将 class 放在括号中以澄清 python。请帮忙

setattr将 object 和属性名称作为单独的 arguments:

setattr(Firebender, 'points', 1)

但是写起来更简单

Firebender.points = 1

当您要更改的属性的名称存储在变量中时, 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