Bareword found where operator expected at 错误

本文通过一个具体的例子展示了在Python中定义类时常见的语法错误,并解释了如何避免这些错误。同时,介绍了类变量与实例变量的区别及使用场景。
部署运行你感兴趣的模型镜像

今天写了个简单的python程序,运行的时候居然出现以下错误:

Bareword found where operator expected at.......

 

 

Bareword found where operator expected at classTest.py line 6, near "def"
        (Missing semicolon on previous line?)
Bareword found where operator expected at classTest.py line 9, near ")
        def"
        (Missing operator before def?)
Bareword found where operator expected at classTest.py line 12, near ")
        def"
        (Missing operator before def?)
syntax error at classTest.py line 1, near "class Wallet:"
syntax error at classTest.py line 3, near "):"
Execution of classTest.py aborted due to compilation errors.

 

我的代码如下:

class Wallet:
    walletCnt=0;
    def __init__(self,balance =0):
        self.balance =balance
        Wallet.walletCnt+=1
    def getPaid(self,amnt):
        self.balance+=amnt
        self.displayBalance()   
    def spend(self,amnt):
        self.balance-=amnt
        self.displayBalance()
    def displayBalance(self):
        print 'New Balance:s%.2f' % self.balance
       
myWallet = Wallet(2);
youWallet = Wallet(2);

print myWallet.walletCnt;
print youWallet.walletCnt;


w= Wallet(50.0);
w.getPaid(100);

print w.balance;
print myWallet.walletCnt;
print youWallet.walletCnt;
print w.walletCnt;

print myWallet.balance;

 

 

我彻底无语了,自己检查了几次实在是找不出问题在哪,于是google,还真有人遇到过类似的问题,不过跟我的还是不一样,他出现这些问题的原因在于运行时候路径写错了。

 

受到启发,检查了一下,发现彻底让我晕死,我写成了perl classTest.py

 

 

难怪!!!刚跑完一些perl脚本,脑子还没换过来。NND!

下次要仔细!犯这种错误不抽自己嘴巴实在是。。。。。。

 

关于这个简单程序,有几点需要说明:

 

   1 walletCnt=0;  属于类变量,在任何一个对象中修改此变量将应用到所有的对象;

 

    2self.balance+=amnt balance为对象的变量,只属于对象,每个对象中的值不相同。

 

运行结果:

D:/Python>python classTest.py
2
2
New Balance:s150.00
150.0
3
3
3
2

 

 

 

 

 

 

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惹不起的程咬金

来都来了,不赏点银子么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值