Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - ImportError: cannot import name 'Book' from 'book'

I'm running a code which find out the center point of grid:

This is the content of book.py:

class Book():
    favs = [] #class

    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def is_short(self):
        if self.pages < 100:
            return True

    #What happens when you pass object to print?
    def __str__(self):
        return f"{self.title}, {self.pages} pages long"

    #What happens when you use ==?
    def __eq__(self, other):
        if(self.title == other.title and self.pages == other.pages):
            return True
    
    #It's approriate to give something for __hash__ when you override __eq__
    # #This is the recommended way if mutable (like it is here):
    __hash__ = None

    def __repr__(self): #added to make list of items invoke str
        return self.__str__()

This is the content of booksSDK.py:

import sqlite3
from book import Book

def cursor():
    return sqlite3.connect('books.db').cursor()

c = cursor()
c.execute('CREATE TABLE IF NOT EXISTS books (title TEXT, pages INTEGER)')
c.connection.close()

def add_book(book):
    c = cursor()
    c.execute('INSERT INTO books VALUES (?, ?)', (book.title, book.pages))
    c.connection.close()

When I run hello.py, I get the following error:

Traceback (most recent call last):
  File "c:/Users/ivan/Downloads/EXAMPLE/hello.py", line 1, in <module>
    from book import Book
ImportError: cannot import name 'Book' from 'book'

at this line:

from book import Book
import booksSDK

book = Book("Are You My Mother?", 72)
booksSDK.add_book(book)

How can I fix this error? I run the hello.py from Visual Studio Code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...