python 发生异常: AttributeError ‘xxx’ object has no attribute ‘ooo’

 原因: 函数调用发生在变量定义之前
示例分析:
 在apple.py文件中代码如下:
class Apple():
	def __init__(self):
		self.eat()
		self.price
		
	def eat(self):
		print("吃的这个苹果价格为 %d"%self.price)
 
在dog.py文件中代码如下:
from apple import Apple
class Dog():
	def __init__(self):
		self.run()
		self.myApple=Apple()
	def run(self):
		pass
if __name__=="__main__":
	myDog=Dog()
 
代码不难理解,dog模块中调用了apple模块,程序的执行过程大概如下:
1.实例化了一只myDog
 2.在构造myDog期间又例化了一个Apple,对象为myApple
 3.程序进入apple.py文件中,在构造myApple时进入eat( )函数
 4.在eat( )函数中调用了self.price属性
 5.eat( )函数执行结束,定义self.price
看到这应该能找到问题了,步骤4应该在步骤5 之后进行才对
这个问题浪费了近一个小时才找到,debug到怀疑人生
总结: 写程序时一定要规范,先写变量,再写函数
def fun(self):
	num=0            #变量1
	charList=[0,1,2] #变量2
	fun00()          #函数1
	fun01()          #函数2
                


















