读书人

class _init_self的意义。解决思路

发布时间: 2012-04-25 19:32:32 作者: rapoo

class __init__,self的意义。

Python code
class TheThing(object):def __init__(self):self.number = 0


每一个类都需要一个__init__么。~



课本上的内容:

接下来,看到__init__ 函数了吗?这就是你为Python class 设置内部变量的方式。你可以使用. 将
它们设置到self 上面。另外看到我们使用了add_me_up() 为你创建的self.number 加值。后面你可以看
到我们怎样可以使用这种方法为数字加值,然后打印出来。

可是我不太懂。
希望达人解释下。
我有学过一点C++,

[解决办法]
__init__是python类的constructor,但是不是必须的.self用来指代类自身,类似c++的this
类的成员变量任何时候都可以赋值,这也是动态语言的优势
看例子

Python code
class test1(object):    def print_me(self):        self.msg = 'test.msg'        print 'test1:print_me()'        print 'self.msg='+self.msg        class test2(object):    def __init__(self):        self.msg = 'test2.msg'    def print_me(self):        print 'test2:printme()'        print 'self.msg='+self.msgt1 = test1()t1.print_me()print '==============='t2 = test2()print t2.msgt2.print_me() 

读书人网 >perl python

热点推荐