现在的位置: 首页 > 综合 > 正文

初学python class 注意构造函数__init__(self)

2013年04月09日 ⁄ 综合 ⁄ 共 727字 ⁄ 字号 评论关闭

学习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

抱歉!评论已关闭.