返回基于Python中的优class\uuu.\uu name_uu的对象

2024-05-29 00:03:16 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个超类(为了简单起见,我将其称为“哺乳动物”,Dog、Monkey和Bear类从中继承方法。一些继承的方法返回的对象需要与调用该对象的类相同。例如,Dog.find(...)应该返回Dog对象。但是由于find()方法是从哺乳动物那里继承的,所以该方法不能被显式地编码为return Dog(...)。它需要能够返回狗、猴子、熊或哺乳动物对象,这取决于self.__class__.__name__的值。在

我已经用return eval(self.__class__.__name__)(...)实现了这一点,但我宁愿避免使用eval。有更好的方法吗?在


Tags: 对象方法nameself编码returnevalfind
2条回答

使用classmethod创建工厂:

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

只要试试return self.__class__()

相关问题 更多 >

    热门问题