如果你只是尋找直線上升的功能,畢波多黎各有正確的答案。但是,您提到了範圍設定,並且您的代碼看起來像試圖成爲一個班級。所以讓我們建立一個適當的課堂。
在類中函數被稱爲方法。這是一種說法「的一個奇特的方式對這些功能範圍是在類‘一’
import random
class One(object):
home_goals =()
away_goals =()
def playGame(self):
self.home_goals = round(random.uniform(0,10.0))
self.away_goals = round(random.uniform(0.1,10.0))
return self.home_goals, self.away_goals
def determineWinner(self):
if not self.home_goals or not self.away_goals:
print("Teams must play game first!")
return None
if self.home_goals > self.away_goals:
winner = ("home")
elif self.home_goals == self.away_goals:
winner = ("draw")
else:
winner = ("away")
print(winner)
return winner
## usage
one_obj = One() #create instance of One()
home, away = one_obj.playGame()
game1 = one_obj.determineWinner()
one_obj.playGame() #play a new game
game2 = one_obj.determineWinner()
類有一個叫做‘自我’特殊的變量,它是這樣的對象one_obj
股份變量home_goals
和away_goals
兩種方法之間。
如果我們不使用自己,我們需要輸出從一個方法保存,並將它們傳遞到另一個。
你可以用一個裝飾做這個叫@staticmethod
import random
# still using a class but without self
class Two(object):
@staticmethod
def playGame():
home_goals = round(random.uniform(0, 10.0))
away_goals = round(random.uniform(0.1, 10.0))
return home_goals, away_goals
@staticmethod
def determineWinner(home_goals, away_goals):
if not home_goals or not away_goals:
print("Teams must play game first!")
return None
if home_goals > away_goals:
winner = ("home")
elif home_goals == away_goals:
winner = ("draw")
else:
winner = ("away")
print(winner)
return winner
two_obj = Two()
home, away = two_obj.playGame()
game1 = two_obj.determineWinner(home, away)
一個類的點基本上被忽略,只是一個對象來保存兩個函數。但在你的問題中,你必須引用實例two_obj
以調用這些方法。
在Bi Rico的例子中,函數在GLOBAL範圍內。在上面的例子中,方法(也就是類中的函數)在類的範圍內。
有可能引用靜態方法沒有實例化類Two()
:
home, away = Two.playGame()
game1 = Two.determineWinner(home, away)
一切都應該曾經在這裏打字時,我犯了一個錯誤後級縮進。 – Bob457678y
現在壓痕看起來是否正確? – senshin
在python中,如果你想返回兩個東西,你可以使用'return a,b'而不是兩個return語句。 –