3

I'm trying to make a really simple command-based python script, and get commands from the terminal's input, but it's not detecting the value of the variable... I'm not good at explaining, so here's my code:

a = 0
b = 0

class commands:
    def add():
        a = int(input("first number "))
        b = int(input("second number "))
        print(a + b)

commander = commands
cmd = input("what command ")
commander.cmd()

When I run it, it gives me an error saying Exception has occurred: AttributeError type object 'commands' has no attribute 'cmd' I'm still relatively new to Python, so sorry if it's something really obvious. Thank you, and any help is appreciated.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • To create an instance of your `commands` class, you need to call it by using `commander = commands()` (note the parentheses at the end). It's also unclear how you expect the instance to have a `cmd` (or any other) attributes at all. What strings should be turned into attributes? – martineau Jun 30 '19 at 02:31

2 Answers2

5

you just have to do:

getattr(commander, cmd)()
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
0

I have modified your code with if-else so that you can get your desired result:-

a = 0
b = 0

class commands:
    def add(self):
        a = int(input("first number "))
        b = int(input("second number "))
        print(a + b)

commander = commands()
cmd = input("what command ")
print(cmd)
if cmd == 'add':
   commander.add()

I hope it may help you.

Rahul charan
  • 765
  • 7
  • 15