关于python里定义class的问题

问下为什么要__init__?有什么用?... 问下为什么要__init__? 有什么用? 展开
 我来答
百度网友15eb9c1
推荐于2016-02-12 · 超过19用户采纳过TA的回答
知道答主
回答量:39
采纳率:0%
帮助的人:35.8万
展开全部
对象构造后第一个调用的函数,在python里面实例的属性是可以动态构建的,在类里面定义的属性是类属性,不是实例属性,定义实例自己的属性的最好地方是__init__函数里面。
比如
class TEST():
class_attr #类属性,通过TEST.class_attr调用,如果用instance.class_attr调用实际上是声明类另一个实例属性,与之前的TEST.class_attr不是一个东西了

def __init__(self,other):

self.class_attr #实例属性,与之前的那个属性处于不同的名字空间了,不是一个东西。

self.other=other

总之,__init__可以用来声明实例属性,以及进行必要的初始化。
wode5130
2012-07-06 · TA获得超过638个赞
知道小有建树答主
回答量:423
采纳率:100%
帮助的人:334万
展开全部
它是python语法中固定的方法,主要作用就是创建类实例后做初始化工作,创建时调用__new__,初始化时调用__init__。这些方法叫做魔法方法,由python解释器调用
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
鸿蒙始兴
2015-08-23 · TA获得超过2010个赞
知道小有建树答主
回答量:1080
采纳率:48%
帮助的人:117万
展开全部

#----------------------------------------------------------------------

#  Copyright (c) 1999-2001, Digital Creations, Fredericksburg, VA, USA

#  and Andrew Kuchling. All rights reserved.

#

#  Redistribution and use in source and binary forms, with or without

#  modification, are permitted provided that the following conditions are

#  met:

#

#    o Redistributions of source code must retain the above copyright

#      notice, this list of conditions, and the disclaimer that follows.

#

#    o Redistributions in binary form must reproduce the above copyright

#      notice, this list of conditions, and the following disclaimer in

#      the documentation and/or other materials provided with the

#      distribution.

#

#    o Neither the name of Digital Creations nor the names of its

#      contributors may be used to endorse or promote products derived

#      from this software without specific prior written permission.

#

#  THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS AND CONTRIBUTORS *AS

#  IS* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED

#  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A

#  PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL

#  CREATIONS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,

#  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,

#  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS

#  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND

#  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR

#  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE

#  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH

#  DAMAGE.

#----------------------------------------------------------------------



"""Support for Berkeley DB 4.3 through 5.3 with a simple interface.


For the full featured object oriented interface use the bsddb.db module

instead.  It mirrors the Oracle Berkeley DB C API.

"""


import sys

absolute_import = (sys.version_info[0] >= 3)


if (sys.version_info >= (2, 6)) and (sys.version_info < (3, 0)) :

    import warnings

    if sys.py3kwarning and (__name__ != 'bsddb3') :

        warnings.warnpy3k("in 3.x, the bsddb module has been removed; "

                          "please use the pybsddb project instead",

                          DeprecationWarning, 2)

    warnings.filterwarnings("ignore", ".*CObject.*", DeprecationWarning,

                            "bsddb.__init__")


try:

    if __name__ == 'bsddb3':

        # import _pybsddb binary as it should be the more recent version from

        # a standalone pybsddb addon package than the version included with

        # python as bsddb._bsddb.

        if absolute_import :

            # Because this syntaxis is not valid before Python 2.5

            exec("from . import _pybsddb")

        else :

            import _pybsddb

        _bsddb = _pybsddb

        from bsddb3.dbutils import DeadlockWrap as _DeadlockWrap

    else:

        import _bsddb

        from bsddb.dbutils import DeadlockWrap as _DeadlockWrap

except ImportError:

    # Remove ourselves from sys.modules

    import sys

    del sys.modules[__name__]

    raise


# bsddb3 calls it db, but provide _db for backwards compatibility

db = _db = _bsddb

__version__ = db.__version__


error = db.DBError  # So bsddb.error will mean something...


#----------------------------------------------------------------------


import sys, os


from weakref import ref


if sys.version_info < (2, 6) :

    import UserDict

    MutableMapping = UserDict.DictMixin

else :

    import collections

    MutableMapping = collections.MutableMapping


class _iter_mixin(MutableMapping):

    def _make_iter_cursor(self):

        cur = _DeadlockWrap(self.db.cursor)

        key = id(cur)

        self._cursor_refs[key] = ref(cur, self._gen_cref_cleaner(key))

        return cur


    def _gen_cref_cleaner(self, key):

        # use generate the function for the weakref callback here

        # to ensure that we do not hold a strict reference to cur

        # in the callback.

        return lambda ref: self._cursor_refs.pop(key, None)


    def __iter__(self):

        self._kill_iteration = False

        self._in_iter += 1

        try:

            try:

                cur = self._make_iter_cursor()


                # FIXME-20031102-greg: race condition.  cursor could

                # be closed by another thread before this call.


                # since we're only returning keys, we call the cursor

                # methods with flags=0, dlen=0, dofs=0

                key = _DeadlockWrap(cur.first, 0,0,0)[0]

                yield key


                next = getattr(cur, "next")

                while 1:

                    try:

                        key = _DeadlockWrap(next, 0,0,0)[0]

                        yield key

                    except _bsddb.DBCursorClosedError:

                        if self._kill_iteration:

                            raise RuntimeError('Database changed size '

                                               'during iteration.')

                        cur = self._make_iter_cursor()

                        # FIXME-20031101-greg: race condition.  cursor could

                        # be closed by another thread before this call.

                        _DeadlockWrap(cur.set, key,0,0,0)

                        next = getattr(cur, "next")

            except _bsddb.DBNotFoundError:

                pass

            except _bsddb.DBCursorClosedError:

                # the database was modified during iteration.  abort.

                pass

# When Python 2.4 not supported in bsddb3, we can change this to "finally"

        except :

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
kaisa1028
2012-07-08 · TA获得超过1.1万个赞
知道大有可为答主
回答量:5429
采纳率:28%
帮助的人:2569万
展开全部
__init__就是相当于别的oop语言里的构造函数
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
Lcisware
2012-07-05 · TA获得超过619个赞
知道小有建树答主
回答量:846
采纳率:50%
帮助的人:343万
展开全部
可以在创建对象的时候传入参数,参数该如何使用就是init函数做的。类似c++ 的构造函数。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(3)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式