cql123 发表于 2018-5-30 23:43:06

代码报错,不知道原因,请帮忙分析下。

这是视频38中的代码:
import random as r
class Fish:
    def _init_(self):
      self.x=r.randint(0,10)      
      self.y=r.randint(0,10)
            
    def move(self):
      self.x=self.x-1
      print('我的位置是:',self.x,self.y)
但是我运行代码的话,会报错,错误如下所示:
>>> a=Fish()
>>> a.move()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
    a.move()
File "C:/Users/cui qing long/Desktop/PyTHON/class1.py", line 11, in move
    self.x=self.x-1
AttributeError: 'Fish' object has no attribute 'x'   


我用的python的版本为3.7,是这个原因吗?
   

cql123 发表于 2018-5-31 07:06:21

已查明原因,init前后为双下划线__init__,我写成单下划线了,导致该函数无效,坐标(x,y)未生成。

BngThea 发表于 2018-5-31 07:46:10

init左右两边是两个下划线

冬雪雪冬 发表于 2018-5-31 08:10:23

init前后各两个下划线。

thexiosi 发表于 2018-5-31 08:34:06

hi 原因如下

def _init_(self):    #应该是 __init__

理想小青年 发表于 2018-5-31 08:40:19

本帖最后由 理想小青年 于 2018-5-31 08:42 编辑

import random as r
class Fish:
    def __init__(self):   
      self.x=r.randint(0,10)      
      self.y=r.randint(0,10)
            
    def move(self):
      self.x=self.x-1
      print('我的位置是:',self.x,self.y)
少了两个下划线 AttributeError: 'Fish' object has no attribute 'x'
提示数 没有'x'的属性,就像没有定义这个数一样,所以你就去传参的地方找错误即可{:10_256:}
页: [1]
查看完整版本: 代码报错,不知道原因,请帮忙分析下。