-5

我是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() 
4

2 回答 2

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()
于 2013-07-04T17:06:54.340 回答
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类主体之外。

于 2013-07-04T17:06:57.600 回答