我是python的新手很抱歉,如果这非常简单,但我有点卡住了,我已经查看了关于抛硬币的其他问题,但这比那些更简单:
简单地说,为什么我的前卫不会工作?
class Coin:
showing_heads=True
value=1
def show(self):
if (self.showing_heads==True):
return "Heads"
else:
return "Tails"
def turn(self):
if (self.showing_heads==True):
self.showing_heads=False
else:
self.showing_heads=True
def run_cointoss(2):
coin1=Coin()
coin2=Coin()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
print "Turn them over"
coin1.turn()
coin2.turn()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
答案 0 :(得分:1)
你不应该在coin
类中创建硬币:
def run_cointoss(2):
coin1=Coin()
coin2=Coin()
而是在类定义
之后创建它们class Coin:
showing_heads=True
value=1
def show(self):
if (self.showing_heads==True):
return "Heads"
else:
return "Tails"
def turn(self):
if (self.showing_heads==True):
self.showing_heads=False
else:
self.showing_heads=True
# Class definition is done
def run_cointoss():
coin1=Coin()
coin2=Coin()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
print "Turn them over"
coin1.turn()
coin2.turn()
print "This is coin1"
print coin1.show()
print "This is coin2"
print coin2.show()
run_cointoss()
答案 1 :(得分:1)
一个问题是你在函数参数中使用2。函数参数期望有效标识符,2
不是有效标识符:
>>> def func(x):
pass
...
>>> def func(x = 2):
pass
...
您的错误:
>>> def func(2):
pass
File "<ipython-input-234-dc2d2489d3d8>", line 1
def func(2):
^
SyntaxError: invalid syntax
其次,如果您的原始代码在问题正文中缩进,那么您应该将函数run_cointoss
的定义移到类体之外。