初学Python,遇到AttributeError: 'Person' object has no attribute 'firstname'问题的解决方法

      最近在学习Python的类和对象内容时,尝试一个关于Person类的代码,出现一个问题:AttributeError: 'Person' object has no attribute 'firstname'。

class Person :
	hair = 'black'
	def __init__(self,firstname = 'charlie',age = 8):
		self.firstname = firstname
		self.age = age
	def say(self,content):
	   print(content)
p = Person()
print(p.firstname,p.age)

       百度其他人的解决办法都是考虑可能变量名与系统内部的冲突,于是我把name改成firstname,发现问题依然存在。后来我发现网上的代码init前后的下划线比我写的长一点,于是复制粘贴过来,运行果然可以了。

       回去看书,书上也写的很明确是双下画线开头,双下画线结尾。出现这个问题就是自己不认真看书的后果,记录下来警示自己。

猜你喜欢

转载自blog.csdn.net/weixin_39006917/article/details/101697811