开发者

Returning an object based on __class__.__name__ in Python

开发者 https://www.devze.com 2023-03-18 23:20 出处:网络
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 c

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 achi开发者_如何学Goeved this with return eval(self.__class__.__name__)(...), but I'd prefer to avoid using eval. Is there a better way?


Just try return self.__class__()


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'>
0

精彩评论

暂无评论...
验证码 换一张
取 消