-1

I haven't created any classes from scratch before. Any previous ones have been super simple. Am I close to creating the class right? I'm confused on how to call an instance of the class. What I want to do is create a class Book and assign various values (author name, home directory, output directory, function to get title, function to get .html files from home directory, etc). I want to create a new instance of class Book for each bookList[i]. bookList[i] is each book's homeDir. What is my class and/or instance call missing please? Thanks in advance for all help or pointers.

class Book(obj):        
    def __init__(self, inc_dir):
        self.home_dir = inc_dir
        # self.author_name = aName
        # self.target_dir = target_dir

# main #
bookList = getDirs(homeDir) # returns a list. works.
# print("len(bookList): ", len(bookList))     
i = 0    
while i <= len(bookList):
    curBook = Book(bookList[i])
    print("curBook name: " + curBook.home_dir)
    print("Book Path: " + bookList[i])
    i += 1  

Traceback (most recent call last):
    File "D:\Scripts\Python\batch content editing\html_book_builder.py", line 65, in <module>
        class Book(obj):
    NameError: name 'obj' is not defined
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Meghan M.
  • 129
  • 1
  • 13
  • So basically `object` is a predefined default base class. None of the info I was reading ever specifically stated that (to me). This question is a duplicate. After specifically searching for "python class object keyword" it came up with: https://stackoverflow.com/questions/4015417/python-class-inherits-object – Meghan M. Aug 30 '18 at 16:46

3 Answers3

1

You're defining the class Book to inherit from the class obj, and yet there's no such class named obj, hence the error. If you mean for the class Book to inherit from the base class, you should either make it inherit from the class object:

class Book(object):

or simply omit the parent class specification if you're using Python 3.x:

class Book:
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

What's happening is that when you write class Book(obj), the Python interpreter is looking for something named obj. You haven't defined obj yet, so Python complains that nothing named obj has been defined.

You may have seen examples with object as follows:

class Book(object):

These examples are subclassing the already existing object. There isn't a name error because that thing is already defined. In Python 3, you can get rid of the object entirely. You can in Python 2 as well, but the behavior of classes changes a bit in that case (there were quite a few so-called "breaking" changes between 2 and 3).

class Book:
Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37
0

I think it is with obj which is passed as an argument for the Class Book. It is supposed to be object(Lower case) in Python 2.x. In Python 3.x, You can just leave it out!