简体   繁体   中英

Why is the code showing SyntaxError: invalid syntax when I try creating an object of a class? [on hold]

I had created a class called Boy and tried creating an object b1 (b1= Boy()) but this line shows error.

The full code is as follows:

class Boy:
    name='JOHN'
    age='21'
    def say_hello(self):
        print('Hello! My name is %s and I am %s years old' % (self.name,self.age)
b1=Boy()
b1.say_hello()

The error message is as follows:

runfile('C:/Users/kesha/.spyder-py3/edugrad.py', 
wdir='C:/Users/kesha/.spyder-py3')
Traceback (most recent call last):

File "C:\ProgramData\Anaconda3\lib\site- 
packages\IPython\core\interactiveshell.py", line 3325, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)

File "<ipython-input-1-d5ee685f3657>", line 1, in <module>
runfile('C:/Users/kesha/.spyder-py3/edugrad.py', 
wdir='C:/Users/kesha/.spyder-py3')

File "C:\ProgramData\Anaconda3\lib\site- 
packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site- 
packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/kesha/.spyder-py3/edugrad.py", line 13
b1=Boy()
 ^
SyntaxError: invalid syntax

I tried running the same code in python console using Jupyter Notebook and it ran just fine.

Expected Output: Hello. My name is John I am 21 years old.

Just a couple of bugs. First, you forgot the last parenthesis on the print statement. This was actually causing your error. Sometimes errors can be hard to track like this. It's very common to forget a closing paren/bracket/brace, which causes the FOLLOWING line to report the error (thinking it's a part of the previous line.)

Second, for the class to work the way you want, it's more Pythonic (and proper) to use an initialization method to associate the variables with self.

Finally, with Python 2.7 end-of-life coming in 2020, Python's format command is the recommend way to format strings.

class Boy:
    def __init__(self):
        self.name='JOHN'
        self.age='21'

    def say_hello(self):
        #print('Hello! My name is %s and I am %s years old' % (self.name,self.age))
        print('Hello! My name is {} and I am {} years old'.format(self.name,self.age))
b1 = Boy()
b1.say_hello()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM