我正在編寫一個程序,您可以在其中放置主隊,客隊以及比賽結果。我想讓團隊的數據根據這個改變,大部分都會改變。但我不能讓「點數」,「淨勝球」和「打球」(比賽)改變!這是我寫到目前爲止代碼:使用其他屬性的值進行計算的屬性
class team:
def __init__(self, name, wins, drawn, losses, goals_for, goals_against):
self.name = name
self.wins = int(wins)
self.drawn = int(drawn)
self.losses = int(losses)
self.goals_for = int(goals_for)
self.goals_against = int(goals_against)
self.goals_difference = (self.goals_for - self.goals_against)
self.points = ((self.wins * 3) + self.drawn)
self.played = (self.wins + self.drawn + self.losses)
def __repr__(self):
return 'Name:{} P:{} W:{} D:{} L:{} GF:{} GA:{} GD:{} PTS:{}'.format(self.name, self.played, self.wins, self.drawn, self.losses, self.goals_for, self.goals_against, self.goals_difference, self.points)
detroit_red_wings = team("Detroit", 1, 0, 3, 4, 5)
los_angeles_kings = team("LA", 0, 1, 4, 3, 7)
toronto_maple_leafs = team("Toronto", 1, 2, 2, 3, 6)
teamlist = [detroit_red_wings, los_angeles_kings, toronto_maple_leafs]
print(teamlist)
class data_input:
def home_team_input(self):
home_team = input("Type in the home team: ")
for i in teamlist:
if i.name == home_team:
return i
def away_team_input(self):
away_team = input("Type in the away team: ")
for t in teamlist:
if t.name == away_team:
return t
def result_input(self):
goals_home_team = int(input("Type in the number of goals made by the home team: "))
goals_away_team = int(input("Type in the number of goals made by the away team: "))
return (goals_home_team, goals_away_team)
def adding_result():
home_team = data_input.home_team_input()
away_team = data_input.away_team_input()
goals_home_team, goals_away_team = data_input.result_input()
home_team.goals_for += goals_home_team
home_team.goals_against += goals_away_team
away_team.goals_for += goals_away_team
away_team.goals_against += goals_home_team
if goals_home_team > goals_away_team:
home_team.wins += 1
away_team.losses += 1
if goals_home_team < goals_away_team:
away_team.wins += 1
home_team.losses += 1
if goals_home_team == goals_away_team:
home_team.drawn += 1
away_team.drawn += 1
data_input = data_input()
adding_result()
print(teamlist)
我寫的屬性中的指導類team
的__init__
方法,正如你所看到的點依賴於wins
。這一切都適用於我創建對象的時候,但是當我將新遊戲的結果放入points
時不會改變(played
或goals_difference
也不會)。這令我感到驚訝,因爲當我在input
函數中輸入遊戲結果時,其他屬性會發生變化。
這工作得很好!非常感謝你!! –
有一個單獨的更新功能是非常糟糕的。計算結果應該通過@properties或函數訪問,以便它們對於其他項目的當前狀態始終準確。 –
@SteveCohen好點,我目前無法更新我的答案,但我會盡快解決,但我試圖做到簡單,但在這種情況下,簡單只是一種不好的做法。 – miradulo