我曾尝试创建类并定义其对象以查找总和和平均值,但代码不起作用。我已经创建了CricketGame类并创建了模型和对象,但代码仍然不起作用。谁能让我更清楚地使用类对象和模型吗。
class CricketGame:
def __init__(self, name, age, matches, innings, runs_scored, wickets_taken, ball_faced, runs_given, ball_bowled):
self.name = name
self.age = age
self.matches = matches
self.innings = innings
self.runs_scored = runs_scored
self.wickets_taken = wickets_taken
self.ball_faced = ball_faced
self.runs_given = runs_given
self.ball_bowled = ball_bowled
def playerstat(self):
batting_average = self.runs_scored/self.innings
batting_strike_rate = self.runs_scored/self.ball_faced
bowling_average = self.ball_bowled/self.wickets_taken
bowling_strike_rate = self.runs_given/self.wickets_taken
def playerresult(self, batting_average, batting_strike_rate, bowling_average, bowling_strike_rate):
print "Batting Average : ", batting_average
print "Batting Strike Rate : ", batting_strike_rate
print "Bowling Average : ", bowling_average
print "Bowling Strike rate : ", bowling_strike_rate
def playerinfo(self):
print "Player's Name : ", self.name
print "Age : ", self.age
print "Matches : ", self.matches
print "Inning Played :", self.innings
print "Run Score : ", self.runs_scored
print "Wicket Taken :", self.wickets_taken
print "Ball Faced :", self.ball_faced
print "Runs Given : ", self.runs_given
print "Ball Bowled : ", self.ball_bowled
name = raw_input("Enter the name of the player : ")
age = input("Enter the age of the player : ")
matches = input("Enter the number of matches played : ")
innings = input("Enter the innings played : ")
runs_scored = input("Enter total runs scored: ")
wickets_taken = input("Enter the total wickets taken : ")
ball_faced = input("Enter the total number of ball faced : ")
runs_given = input("Enter the total runs given : ")
ball_bowled = input("Enter the total ball bowled : ")
player = CricketGame(name, age, matches, innings, runs_scored, wickets_taken, ball_faced, runs_given, ball_bowled)
player.playerinfo()
player.playerstat()
player.playerresult()
playerresult((函数需要4个参数,而您传递的是0个参数。当您在playerstat((中计算batting_average时,它不会传递给playersresult((函数。您可以将这些变量转换为实例变量,以便从类似这样的另一个方法访问它们。
def playerstat(self):
self.batting_average = self.runs_scored/self.innings
self.batting_strike_rate = self.runs_scored/self.ball_faced
self.bowling_average = self.ball_bowled/self.wickets_taken
self.bowling_strike_rate = self.runs_given/self.wickets_taken
def playerresult(self):
print "Batting Average : ", self.batting_average
print "Batting Strike Rate : ", self.batting_strike_rate
print "Bowling Average : ", self.bowling_average
print "Bowling Strike rate : ", self.bowling_strike_rate
player.playerstat()
创建并"忘记"了4个变量,因为您没有保存它们。您可以返回您在player.playerstat()
中计算的内容,并将其分配给4个变量。然后将这些变量作为参数传递给player.playerresult()
。
另一种方法是将这4个变量保存为对象的属性(self.batting_average
等(,并更改player.playerresult()
,使其不接受任何参数,而是打印self.batting_average
等。