初始化Python对象

时间:2015-01-02 02:37:46

标签: python python-3.x initialization

我正在尝试用Dusty Phillips的书“Python 3,面向对象编程”一书来教我自己的Python面向对象编程。在第54和55页,他创建了一个名为Note的类,并鼓励读者重复该示例并使用以下命令从解释器导入模块。但是,当我这样做时,我输入n1 =命令我从解释器获取消息“TypeError:object()没有参数。我在这个对象的实现中遗漏了什么,或者这本书给出了一个错误的例子?你的例子和输入解释器的行完全取自本书,至少我认为我在复制行时没有错误。这是与C ++不同的初始化语法,这让我想知道作者是否给出了一个不好的例子,但是在书中的例子看起来好像他试图通过直接调用对象进行初始化,并且该对象应该识别传递给memo的文本。我也尝试在python 2.7.9和3.4中运行该示例.2看看这是否是版本问题。

译员行

  
    
      

从笔记本导入注意

             

n1 =注意(“hello first”)#代码执行在这里停止错误

             

n2 =注意(“再次问好”)

             

n1.id

             

n2.id

    
  
import datetime

# store the next available id for all new notes
last_id = 0

class Note:
    '''Represent a note in the notebook.  Match against a
       string in searches and store tags for each note.'''
    def _init_(self, memo, tags=''):
        '''initialize a note with memo and optional
            space-seperated tags.  Automatically set the note's
            creation date and a unique id.'''
        self.memo = memo
        self.tags = tags
        self.creation_date = datetime.date()
        global last_id
        last_id += 1
        self.id = last_id

    def match(self, filter):
        '''Determine if this note matches the filter
           text.  Return True if it matches, False otherwise.

           Search is case sensitive and matches both text and 
           tags'''

        return filter in self.memo or filter in self.tags

2 个答案:

答案 0 :(得分:2)

也许做基督徒说的话:用__init__代替_init_。你需要有双下划线而不是单下划线。您可以查看Python Docs

答案 1 :(得分:1)

您在the special __init__ method中缺少双下划线。您只有一个下划线。

您也可以考虑让Note明确继承object,即class Note(object)