[SOLVED] Don't know how to call classes in python using if function

Issue

So I am making a program in which it reads a .txt file and runs different classes; I made it so it opens the file and stores the text in a decision string, Using if decision == "wincode" or "lostcode" I want it to run a specific class like:

class wonToss():
    
    wininput = input("Do you want to choose: ")

    def outChoice():
        print("no error")

    
    def inChoice():
        print("No error")
        


    if wininput == "Indoor":
        inChoice()
    elif wininput == "Outdoor":
        outChoice() 

I put the "No error" for testing to see if it works

class lostToss():

    def botChoose():
        print("Bot is choosing between Indoor and Outdoor.")
        print(".")
        time.sleep(0.25)
        print("..")
        time.sleep(0.25)
        print("...")
        time.sleep(0.25)
        print("")
        choices = ['Indoor', 'Outdoor']
        botting = random.choice(choices)
        print(f"And the bot chose: {botting}")
        time.sleep(2)

    botChoose()

And this is the second class. So now, I want it to check the code and class the specific class.

This is the check code:

f=open("TossDecision.ch", "r")

if f.mode == 'r':
    decision = f.read()

if decision == "jhe78r2dbgv67t2yhdb7vgr":
    print("")
    wonToss()

elif decision == "jhe78rnxshwdn7wgh89u3cn":
    print("")
    lostToss()

else:
    print("Toss Decision changed! Re-run the PlayGame file.")
    exit()

But the problem is,
When I run the program it just shows:

Do you want to choose (Indoor) or (Outdoor)?: Indoor
Bot is choosing between Indoor and Outdoor.
.
..
...

And the bot chose: Indoor

It calls both the classes. Currently its set to loss. It still calls wonToss() Can anyone help fix this

Solution

Sorry, but you are using classes totally wrong.

Please read on Object-oriented programming.

  1. A class is a blueprint for an object.

  2. In most times, you instantiate an object of the class, and work with it. Like this:

class Mything:
    def InChoice(self):
        print("No errror indoors")
    def OutChoice(self):
        print("No error outdoors")
    def ask_choice(self):
        wininput = input("Do you want to choose: ")
        if wininput == "Indoor":
           self.InChoice()
        elif wininput == "Outdoor":
           self.OutChoice()

Then in your program you do:

  choice_object=Mything()
  choice_object.ask_choice()

Answered By – Gnudiff

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *