我将向您展示我的脚本,然后解释我想做什么
class Animal(object):
def __init__(self,name=None):
self.name=name
if name=="dog":
object=Dog()
if name=="cat":
object=Cat()
def execute(self):
print("I am animal")
class Dog:
def __init__(self):
pass
def execute(self):
print("I am a dog")
class Cat:
def __init__(self):
pass
def execute(self):
print("I am a cat")
if __name__ =="__main__":
instanceAnimal=Animal("cat") # I would like to get "I am a cat" but I got "I am animal"
instanceAnimal.execute()
我知道这不是固有的好方法,但是我有一个用例,我想实例化一个Animal实例,并在输入中指定一个名称,该类将调用相应的execute。
希望我的例子很清楚
答案 0 :(得分:2)
使用元类和继承的干净解决方案:
class AnimalType(type):
_classes = {}
def __init__(cls, name, attribs, bases):
super(AnimalType, cls).__init__(name, attribs, bases)
cls._classes[name.lower()] = cls
class Animal(object):
__metaclass__ = AnimalType
def __new__(cls, name=None):
newcls = type(cls)._classes.get(name, Animal)
return object.__new__(newcls, name)
def __init__(self, name=None):
self.name = name
def execute(self):
print("I am animal")
class Dog(Animal):
def execute(self):
print("I am a dog")
class Cat(Animal):
def execute(self):
print("I am a cat")
如果您根本不想继承,只需使用工厂函数即可:
class Animal(object):
def execute(self):
print("I am animal")
class Dog:
def execute(self):
print("I am a dog")
class Cat:
def execute(self):
print("I am a cat")
_clsmap = {
"animal": Animal,
"dog": Dog,
"cat": Cat
}
def make_animal(name):
return _clsmap.get(name, Animal)()
答案 1 :(得分:1)
尽管继承是最佳解决方案,但OP专门要求其他解决方案
object = Dog()
或object = Cat()
无用。它将Dog
或Cat
实例分配给局部变量object
,仅此而已。它不会将其绑定到任何东西。
您将必须在Animal
中保留对其的引用,并将Animal.execute
绑定到适当的execute
方法。
此外,您可以使用字典使初始化更加简洁:
class Dog:
def execute(self):
print("I am a dog")
class Cat:
def execute(self):
print("I am a cat")
class Animal(object):
names_to_classes = {'dog': Dog, 'cat': Cat}
def __init__(self, name=None):
self.name = name
try:
self.object = self.names_to_classes[name]()
except KeyError:
raise TypeError('name must be either "dog" or "cat"')
def execute(self):
self.object.execute()
instanceAnimal = Animal("cat")
instanceAnimal.execute()
instanceAnimal = Animal("dog")
instanceAnimal.execute()
instanceAnimal = Animal("penguin")
instanceAnimal.execute()
输出
I am a cat
I am a dog
TypeError: name must be either "dog" or "cat"
此方法的缺点在于,Dog.__init__
和Cat.__init__
应该接受相同的参数。
答案 2 :(得分:0)
这是您实现所需目标的方法:
&