学习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 += more
AttributeError: 'TheThing' object has no attribute 'number'
检查了很久不知道哪里有错误,到最后拷贝源代码是发现一点点变化 就是__init__(self)的"_"不一般长 才发现python的构造函数 __init__(self)要用两个"_"下划线
练习代码:
class TheThing(object):
def __init__(self):
self.number=0
def some_function(self):
print "I got called."
def add_me_up(self,more):
self.number += more
return self.number
#two different things
a=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.number
print b.number