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.
3 Answers 3
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()
Syntactically, the code is valid.
2 Comments
SyntaxError eitherYou 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.
1 Comment
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 -> Openand open this file - A new window opens with your source code inside.
- Now, press
F5or sayRun -> 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.
SyntaxErrorhere,self.ais not actually calling anything, instead this syntax returns a function, that when called evaluatesAbc.a(self). You want bothself.b()andself.a()in your code.