user179067
user179067

Reputation: 9

Class instance declaration syntax error in Python

I am trying to play with classes in python. I tried to run the following code.

class Abc:
    def a(self):
        print ("not to be seen")
    def b(self):
        print("inaccessible is")
        self.a

say = Abc()
say.b

I am expecting the output as

inaccessible is
not to be seen

Instead I get the following output:

SyntaxError: invalid syntax

with say highlighted.

Please somebody point out what I am doing wrong.

Edit: I'm using IDLE GUI. Python 33 says the Python docs.

Upvotes: 0

Views: 4476

Answers (3)

Johannes P
Johannes P

Reputation: 906

OK, I could reproduce your error by installing idle for Python 3.3.0. I'm sorry that we all suspected that you didn't include the whole error message because IDLE doesn't produce more than a red SyntaxError: invalid syntax. There is nothing wrong with your code, nor your class definition.

I guess, you're just pasting the code as-is into your Python shell window. This way, things won't work because the indentation doesn't get produced correctly. Try pasting the line class Abc: into your shell window and press Enter. You will see that IDLE automatically indents the next line with a tab. This is the correct indentation for the following line, so when you enter it, you need to paste def a(self): without any extra indentation! If you paste line by line and reduce the indentation by one where needed and terminate your class definition with an extra Enter, your code gets executed correctly.

However, you should better use the following method:

  • Paste your file into an editor and save it as whatever.py
  • In IDLE, choose File -> Open and open this file
  • A new window opens with your source code inside.
  • Now, press F5 or say Run -> Run Module
  • Your code will be executed and the result displayed in the Python Shell.

Or, even better, use Python directly in the shell by executing python whatever.py directly.

Upvotes: 0

Johannes P
Johannes P

Reputation: 906

You almost had it. You need to call the functions by adding (), like so:

class Abc:
    def a(self):
        print ("not to be seen")
    def b(self):
        print("inaccessible is")
        self.a()

say = Abc()
say.b()

Actually I'm puzzled why your code throws a syntax error. In Python, it is valid to state a function.

Upvotes: 2

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

Python likes to make syntax very clear - the ()s after a function are not optional when calling a function without parameters like in some other languages.

You're not calling the functions just 'stating' them.

Try

class Abc:
    def a(self):
        print ("not to be seen")
    def b(self):
        print("inaccessible is")
        self.a()

say = Abc()
say.b()

Here is the code working.

Syntactically, the code is valid.

Upvotes: 2

Related Questions