How to fix: Object has no attribute, in python?

Asked

Viewed 405 times

-1

I’m new in python and I don’t understand this attribute error that he talks about. For me the code is correct.

class Notebook:

    def __Init__(self):
    self.__notes = list()


    def storeNote(self,note):
    self.__notes.append(note)

a = Notebook()
print(a.storeNote(3))

The code is exactly like this in my compiler.

follows a link for you to see the code in action with the error appearing.

https://repl.it/repls/DimgrayOutgoingGui

1 answer

2


This is a typo, you named the constructor as:

__Init__

When it should be with minuscule letters:

__init__

That is, without the __init__ the self.__notes cannot be "declared".

See how it works https://repl.it/repls/WoodenConcreteObjectcode:

class Notebook:

    def __init__(self):
        self.__notes = list()


    def storeNote(self,note):
        self.__notes.append(note)


a = Notebook()
print(a.storeNote(3))

It is important to note that storeNote does not return anything, so the result in print will be None, could do something like:

class Notebook:

    def __init__(self):
        self.__notes = list()


    def storeNote(self,note):
        self.__notes.append(note)


    def getNotes(self):
        return self.__notes


a = Notebook()
a.storeNote(3)
a.storeNote(4)
a.storeNote(10)
print(a.getNotes())

Or even directly access the object (which I personally don’t like):

a = Notebook()
a.storeNote(3)
a.storeNote(4)
a.storeNote(10)
print(a.__notes)

I want to make it clear also that list() if it is a function to convert some specific types into list, that is to say it has generated a list for you because list() always returns a list for "convenience", even if empty, in the case how you did not pass the value in the parameter it gave you an empty list, but you could just do this self.__notes = [], thus:

class Notebook:

    def __init__(self):
        self.__notes = []


    def storeNote(self,note):
        self.__notes.append(note)


    def getNotes(self):
        return self.__notes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.