今天写了个简单的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
本文通过一个具体的例子展示了在Python中定义类时常见的语法错误,并解释了如何避免这些错误。同时,介绍了类变量与实例变量的区别及使用场景。
2862

被折叠的 条评论
为什么被折叠?



