【发布时间】:2014-12-05 19:07:01
【问题描述】:
我正在使用 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
我的程序需要接收大量动物并将它们分配给正确的类——我需要正确的属性和方法。我希望 做的是修改 Animal 构造函数,这样如果 name 参数类似于“Finn the Dog”或“Jake the Human”,它(构造函数)会返回该类的实例“狗”或“人”,带有适当的方法和属性。现在,我知道我可以轻松编写一个函数,该函数将字符串和类作为参数,构造一个字典,其中键是给定类的子类的名称,查找包含在字符串中的字典元素, 并返回 that 类的对象。我的问题是是否有办法将它编码到 Animal 类本身中,这对我来说似乎更优雅(也更容易维护)。
【问题讨论】:
-
为什么你觉得在 Animal 类中编码更优雅?一般来说,让一个类的行为依赖于它的子类有点可疑。您最好创建一个选择正确子类的工厂函数。
-
您想要的是 C++ 中所谓的“虚拟构造函数”,是的,可以用 Python 实现它(就像在 C++ 中一样)。大多数人只是编写一个“类工厂”函数,它知道所有可能的类并选择合适的类。我会看看能不能想出一个简单的例子来按照你想要的方式做。
-
@martineau 我很感激!
标签: python oop inheritance