我正在使用 Python 2.7.8。下面是我正在处理的问题的轻微变体。
我编写了大量的自定义类,其中的继承就像一棵树。以下示例很好地封装了该行为:
import random
class Animal(object):
def __init__(self, name):
self.name = name
self.can_own_pets = False #most Animals cannot own pets
self.get_features()
def give_pet(self, pet):
if not self.can_own_pets:
print(self.name+' cannot own a pet!')
else:
self.pets.append(pet)
def is_hungry(self):
return random.choice([True, False])
def get_features(self):
"""
In some classes, get features will be a function
that uses self.name to extract features.
In my problem, the features are extracted
with regular expressions that are determined by
by the class.
"""
pass
class Human(Animal):
def __init__(self, name):
super(Human, self).__init__(name)
self.can_own_pets = True
self.pets = []
class Dog(Animal):
def __init__(self, name):
super(Dog, self).__init__(name)
def bark(self):
print 'WOOF'
def get_features(self):
if 'chihuahua' in self.name:
self.is_annoying = True
elif 'corgi' in self.name:
self.adorable = True
我的程序需要接收大量动物并将它们委托(delegate)给正确的类——我需要正确的属性和方法。我喜欢做的是修改 Animal 构造函数,以便如果名称参数类似于“Finn the Dog”或“Jake the Human”,它(构造函数)返回该类的一个实例“狗”或“人”,具有适当的方法和属性。现在,我知道我可以轻松地编写一个函数,该函数将字符串和类作为参数,构造一个字典,其中键是给定类的子类的名称,查找包含在字符串中的字典元素,并返回 that 类的对象。我的问题是是否有一种方法可以将其编码到 Animal 类本身中,这对我来说似乎更优雅(也更易于维护)。
请您参考如下方法:
这是一个实现——
def _get_all_subclasses(cls):
for scls in cls.__subclasses__():
yield scls
for scls in _get_all_subclasses(scls):
yield scls
class Animal(object):
@staticmethod
def from_string(s):
for cls in _get_all_subclasses(Animal):
# Somehow pick the class based on the string... This is a really simple example...
if cls.__name__ in s:
return cls()
raise ValueError('Bummer. Animal has not been discovered.')
class Dog(Animal):
pass
class Cat(Animal):
pass
class Lion(Cat):
pass
print Animal.from_string('is a Dog')
print Animal.from_string('is a Cat')
print Animal.from_string('Lions!!!')
print Animal.from_string('Lockness Monster')
这里有限制
- 所有构造函数都需要几乎相同,这意味着
Cat.__init__基本上需要做与Human.__init__相同的事情。 - 创建实例后,您的代码需要具有处理
Cat、Human、Dog等的逻辑。在某些情况下,这是好的(例如,代码实际上只关心它正在与Animal一起工作),但通常不是(毕竟,猫可以在栅栏上行走,但人类不能)。
一般来说,我喜欢遵循的原则是尝试让我的函数的输入变得宽松(它是列表还是元组?谁在乎!鸭子打字 FTW!)但要尝试定义明确的输出.我认为从长远来看,这会使界面更易于使用,如果我是审查者,我上面编写的代码可能无法通过代码审查:-)。
