0

So I have a Superclass (which for simplicity I'll call), Mammal, from which classes Dog, Monkey, and Bear inherit methods. Some of the inherited methods return an object that needs to be of the same class it is called from. For example, Dog.find(...) should return Dog objects. But because the find() method is inherited from Mammal, the method can't be coded to explicitly return Dog(...). It would need to be able to return Dog, Monkey, Bear, or Mammal objects, depending on the value of self.__class__.__name__.

I've achieved this with return eval(self.__class__.__name__)(...), but I'd prefer to avoid using eval. Is there a better way?

2
  • Why exactly would you ask a Dog in order to find another Dog? What is the process by which the return value is determined? (Is 'find' really a reasonable name for the method?) Commented Jul 10, 2011 at 7:56
  • That's a good point. I'll agree it's a little awkward. It's basically a model from an MVC framework. I can instantiate Dog objects from rows of a DB table, do things like dog.name = 'Rex' and then dog.save() to update it in the table. This leaves me needing a class that can return Dog objects based on find conditions, but I feel like this is too specialized for the DB wrapper class to do. I'm not the best at class design. Commented Jul 10, 2011 at 17:26

2 Answers 2

3

Just try return self.__class__()

Sign up to request clarification or add additional context in comments.

1 Comment

Ok that works. Not sure why I didn't think of that. Thanks.
3

Use a classmethod to make a factory:

class Mammal(object): @classmethod def new(cls, *args, **kwds): return cls(*args, **kwds) class Dog(Mammal): def find(self): return self.new() >>> d = Dog() >>> d2 = d.find() >>> type(d2) <class '__main__.Dog'> 

2 Comments

Didn't know about @classmethod. I'll keep this in mind. The other answer fits better with what I have already, but I'll try this next time.
@nren Yes, but this fits much better with my understanding of what you're really trying to do :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.