簡體   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