初学python class 注意构造函数

学习python刚到class 做练习时写了_init_(self)构造函数。

运行时总是出现错误:

Traceback (most recent call last): File "C:\Users\Sean\mystuff\ex42.py", line 21, in <module> print a.add_me_up(20) File "C:\Users\Sean\mystuff\ex42.py", line 11, in add_me_up self.number += moreAttributeError: ‘TheThing’ object has no attribute ‘number’

检查了很久不知道哪里有错误,到最后拷贝源代码是发现一点点变化 就是__init__(self)的"_"不一般长 才发现python的构造函数 __init__(self)要用两个"_"下划线

练习代码:

class TheThing(object):def __init__(self): self.number=0def some_function(self): print "I got called."def add_me_up(self,more): self.number += more return self.number#two different thingsa=TheThing()b=TheThing()a.some_function()b.some_function()print a.add_me_up(20)print a.add_me_up(20)print b.add_me_up(30)print b.add_me_up(30)print a.numberprint b.number

,我知道有一种爱情,叫做与你白头,有一种幸福,叫做和你相伴。

初学python class 注意构造函数

相关文章:

你感兴趣的文章:

标签云: