Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class Instance
#1
I have the code attached below. When I run it, after inputting names etc, once you enter first score i get the following error.

Quote:Traceback (most recent call last):
File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 177, in <module>
g = game()
File "/Users/angusgalbraith/Py thon/Darts2021/dartscli1.2.py", line 74, in __init__
self.playerToThrow()
File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 80, in playerToThrow
self.toThrow(1)
File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 93, in toThrow
self.player1.score_entered(2)
File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 39, in score_entered
g.toThrow(next)
NameError: name 'g' is not defined
.

I thought g was an instance of the game class?
Yoriz write Jun-22-2021, 08:24 AM:
File removed, it is now shown in the following post.
Yoriz write Jun-22-2021, 07:58 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
I have the code attached below. When I run it, after inputting names etc, once you enter first score i get the following error.

# create a player class

class player:
    def __init__(self, name):
        self.name = name
        self.stats = {
            "name": self.name,
            "score": 501,
            "sets": 0,
            "legs": 0,
            "180": 0,
            "140": 0,
            "100": 0,
            "80": 0,
            "60": 0,
            "Average": 0,
            "Checkout %": 0,
        }

    def score_entered(self, next):
        next = next
        score = int(input("Enter Score : - "))
        newScore = self.stats['score'] - score
        self.stats['score'] = newScore
        if score == 180:
            self.stats['180'] += 1
        elif score >= 140:
            self.stats['140'] += 1
        elif score >= 140:
            self.stats['100'] += 1
        elif score >= 80:
            self.stats['80'] += 1
        elif score >= 60:
            self.stats['60'] += 1

        if newScore == 0:
            self.leg_won(1)
        else:
            g.toThrow(next)


    def leg_won(self):
        print("leg won")

    def set_won(self):
        pass

    def match_won(self):
        pass


class game:
    def __init__(self):
        # setup players
        player1name = input('Player 1: ')
        self.player1 = player(player1name)
        player2name = input('Player 2: ')
        self.player2 = player(player2name)
    
        # set game parameters
        sets = int(input("Number of Sets: "))
        legs = int(input("Number of Legs per Set: "))
        setstowin = sets//2 + 1
        legstowin = legs//2 + 1
        self.gameState = {
            "setstowin": setstowin,
            "legstowin": legstowin,
            "playerToGo": 1,

        }
        self.legToPlay = 1
        self.setToPlay = 1
        self.winner = False
        self.playerToThrow()


    def playerToThrow(self):
        if self.setToPlay % 2 != 0:
            if self.legToPlay % 2 != 0:
                self.toThrow(1)
            else:
                self.toThrow(2)
        else:
            if self.legToPlay % 2 != 0:
                self.toThrow(2)
            else:
                self.toThrow(1)

    def toThrow(self, player):
        
        if player == 1:
            print(self.player1.stats['name'], "to go you have ", self.player1.stats['score'], "remaining")
            self.player1.score_entered(2)

        else:
            print(self.player2.stats['name'], "to go you have ", self.player2.stats['score'], "remaining")
            self.player2.score_entered(1)
        

    
            
        

    def legWon(self, player):
        if player == 1:
            self.player1.stats['legs']+= 1
            if self.player1.stats['legs'] == self.gameState['legstowin']:
                self.setWon(1)
            else:
                self.player1.stats['score'] = 501
                self.player2.stats['score'] = 501
                self.legToPlay += 1
                self.currentScore()
                self.playerToThrow()
                
                

        else:
            self.player2.stats['legs']+= 1
            if self.player2.stats['legs'] == self.gameState['legstowin']:
                self.setWon(2)
            else:
                self.player1.stats['score'] = 501
                self.player2.stats['score'] = 501
                self.legToPlay += 1
                self.currentScore()
                self.playerToThrow()



    def setWon(self, player):
        if player == 1:
            self.player1.stats['sets']+= 1
            if self.player1.stats['sets'] == self.gameState['setstowin']:
                self.matchWon(1)
            else:
                self.setToPlay += 1
                self.player1.stats['score'] = 501
                self.player2.stats['score'] = 501
                self.player1.stats['legs'] = 0
                self.player2.stats['legs'] = 0
                self.legToPlay = 1
                self.currentScore()
                self.playerToThrow()
        
        else:
            self.player2.stats['sets']+= 1
            if self.player2.stats['sets'] == self.gameState['setstowin']:
                self.matchWon(2)
            else:
                self.setToPlay += 1
                self.player1.stats['score'] = 501
                self.player2.stats['score'] = 501
                self.player1.stats['legs'] = 0
                self.player2.stats['legs'] = 0
                self.legToPlay = 1
                self.currentScore()
                self.playerToThrow()



    

    def matchWon(self, player):
        print("Winner")

    def currentScore(self):
        print("Current Score : ")
        print(self.player1.stats['name'], "Sets ", self.player1.stats['sets'], "Legs ", self.player1.stats['legs'])
        print(self.player2.stats['name'], "Sets ", self.player2.stats['sets'], "Legs ", self.player2.stats['legs'])
        print(self.player1.stats['180'])
        print(self.player1.stats['140'] )



if __name__ == "__main__":
    g = game()
Error:
Traceback (most recent call last): File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 177, in <module> g = game() File "/Users/angusgalbraith/Py thon/Darts2021/dartscli1.2.py", line 74, in __init__ self.playerToThrow() File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 80, in playerToThrow self.toThrow(1) File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 93, in toThrow self.player1.score_entered(2) File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 39, in score_entered g.toThrow(next) NameError: name 'g' is not defined
I thought g was an instance of the game class?

Apologies have reposted with the full. code included.
Reply
#3
g is an instance of game but it is defined at the end of the file so player knows nothing of it
At the minute I don't follow the logic of what the code is doing to advise how you could fix it.

Note:
https://www.python.org/dev/peps/pep-0008/#class-names Wrote:Class names should normally use the CapWords convention.

The player class should not call the game class to make the other player take a turn, The game class should control the flow of players taking turns.
Reply
#4
(Jun-22-2021, 08:04 AM)angus1964 Wrote:
Error:
File "/Users/angusgalbraith/Python/Darts2021/dartscli1.2.py", line 39, in score_entered g.toThrow(next) NameError: name 'g' is not defined
I thought g was an instance of the game class?

Yes indeed. "g" is the object instance of the game class. In the last line you assign this:
    g = game()
So "g" will have a value as soon as game.__init__() has finished. But it does not finish because from this "__init__()" you call "playerToThrow()" which in turn calls "toThrow()" which in turn calls "player*.score_entered()". And there the error arises because "g" still has no value.
Reply
#5
Many thanks ibreeden, I removed the call to playerToThrow, and added after g = game() as g.playerToThrow and it works fine.
Cheers
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Access instance of a class Pavel_47 5 2,091 Nov-19-2021, 10:05 AM
Last Post: Gribouillis
  Can we access instance variable of parent class in child class using inheritance akdube 3 13,991 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Issue referencing new instance from other class nanok66 3 2,232 Jul-31-2020, 02:07 AM
Last Post: nanok66
  Class variable / instance variable ifigazsi 9 4,315 Jul-28-2020, 11:40 AM
Last Post: buran
  Python complains that class instance is not defined colt 3 5,652 Sep-17-2019, 12:32 AM
Last Post: ichabod801
  how to add class instance attributes from list 999masks 2 2,725 Jul-22-2019, 07:59 AM
Last Post: 999masks
  Trying to set an instance variable to current value of a class variable ScottDiesing 3 2,773 Feb-15-2019, 03:12 PM
Last Post: ScottDiesing
  instance of a class in different files DionisiO 2 2,460 Jan-21-2019, 09:38 PM
Last Post: DionisiO
  Printing class instance P13N 2 2,671 Dec-23-2018, 10:28 PM
Last Post: P13N
  How I can create reference to member of the class instance? AlekseyPython 8 3,848 Dec-05-2018, 06:24 AM
Last Post: AlekseyPython

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020