Jon
Jon

Reputation: 1801

Initializing a Python object

I am trying to teach myself object oriented programming in Python with the book "Python 3, Object Oriented Programming", by Dusty Phillips. On pages 54 and 55 he creates a class called Note and encourages the reader to repeat the example and import the module from the interpreter with the following commands. However, when I do, I type the n1 = command I get the message from the interpreter "TypeError: object() takes no parameters. Am I missing something in the implementation of this object, or did the book give a faulty example? Mind you the example and the lines typed into the interpreter are taken exactly from the book, at least I think I made no errors in copying the lines. This is different initialization syntax than C++, which makes me wonder if the author gave a bad example, but in the book example it looks as if he is trying to initialize with a call to the object directly and the object is supposed to recognize the text that gets passed to memo. Also I tried to run the example in python 2.7.9 and 3.4.2 to see if this was a version issue.

Interpreter lines

from notebook import Note

n1 = Note("hello first") # the code execution gets stopped here fur to the error

n2 = Note("hello again")

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

Upvotes: 1

Views: 3216

Answers (2)

Anthony Pham
Anthony Pham

Reputation: 3106

Maybe do what Christian said: Use __init__ instead of _init_. You need to have double underscores not single underscores. You can look at the Python Docs.

Upvotes: 2

Dan
Dan

Reputation: 4663

You are missing double underscores in the special __init__ method. You only have single underscores.

You might also consider having Note explicitly inherit from object, i.e. class Note(object).

Upvotes: 1

Related Questions