views:

183

answers:

1

I want to create class instance inside itself. I tried to it by this way:

class matrix:
    (...)
    def det(self):
        (...)
        m = self(sz-1, sz-1)
        (...)
    (...)

but I got error:

m = self(sz-1, sz-1)

AttributeError: matrix instance has no __call__ method

So, I tried to do it by this way:

class matrix:
    (...)
    def det(self):
        (...)
        m = matrix(sz-1, sz-1)
        (...)
    (...)

and I got another error:

m = matrix(sz-1, sz-1)

NameError: global name 'matrix' is not defined

Of course matrix is not global class. I have no idea how to solve this problem.

+4  A: 
m = self.__class__(sz-1, sz-1)

or

m = type(self)(sz-1, sz-1)
Daniel Roseman
Okay, but type(self) is matrix, isn't it? So why doesn't pablo's second example work? Is it just a fact of life that you can't refer to a class from within itself in Python?
MatrixFrog
I'm deleting my hack of an answer in favor of this gem.
manifest
type(self)() doesn't work for me, but self.__class__() works properly and it's everything I needed. Thanks ;)
pablo