10

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.

5
  • 3
    The last example works for me. Commented Jan 6, 2010 at 18:45
  • As you have it right now, 'm' would be a local variable, not an instance variable, so it will disappear when the det() method returns. This might be appropriate for what you're doing, but when you say you want a "class instance inside itself" it sounds like you might want m to be an instance variable, in which case you need to refer to it as "self.m" Commented Jan 6, 2010 at 18:46
  • What version of Python are you using? Commented Jan 6, 2010 at 18:46
  • The last example works in my Python 2.6.4. I would not expect anything else… Commented Jan 6, 2010 at 22:32
  • the last example could work if matrix was global class, but it isn't. Maybe in python 2.6 it works, I don't know, I'm using 2.5.4. 'm' is local variable because I don't need it outside det() method - I calculate matrix determinant in recursion way. Commented Jan 9, 2010 at 15:56

1 Answer 1

15
m = self.__class__(sz-1, sz-1)

or

m = type(self)(sz-1, sz-1)
Sign up to request clarification or add additional context in comments.

4 Comments

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?
I'm deleting my hack of an answer in favor of this gem.
type(self)() doesn't work for me, but self.__class__() works properly and it's everything I needed. Thanks ;)
@MatrixFrog: For "old-style" classes (python2 classes that don't inherit from object), type(self) is always just <type 'instance'>. The metaclass / new style classes was to enable users to make "real" types.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.