1

What's wrong with this?

class Cat():
    parent = Cat()

NameError: name 'Cat' is not defined

All I wanted to do was to create a class that could be nested to create a tree of category objects. What's the standard way of doing this?

I will eventually be putting this in Django as a Model and syncing with SQLite3. I am a Python newbie. Sorry...

Alveoli
  • 1,202
  • 17
  • 29

3 Answers3

3

You are trying to create a Cat object before the definition of the Cat class is completed.

This version is syntactically legal, but will create an infinite list of cats :

class Cat():
    def __init__(self):
         self.parent = Cat()

What you probably want is something like this:

class Cat():
    def __init__(self, parent=None):
         self.parent = parent
Hans Then
  • 10,935
  • 3
  • 32
  • 51
1
class Cat:
    def __init__(self,parent):
        self.parent = parent

Cat(Cat("dog"))

maybe?

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

Apart from the problems of infinite recursion, it's a mistake to model something as a plain class and then later think about how you would convert it into a Django model. This is because of the object-relational impedence mismatch: Django models are meant to be stored in the database, and relational dbs never match up perfectly with oop concepts.

Luckily, there exists a very good algorithm for spring hierarchical data, which is MPTT, and a good Django implementation of that, django-mptt.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895