使用列表可以节省许多代码行,但它不会扼杀OOP背后的理念吗?因为使用函数式编程来实现它更有意义。你知道吗
在Python中使用列表的示例:
class Pets:
def printlist(self, petslist):
for pet in petslist:
print pet[0]+ " is a "+pet[1]
pet = Pets()
pet.printlist([('parrot','bird'),('snake','reptile'),('dog','mammal')])is a "+pet[1]
使用类继承的示例:
class Pets:
def __init__(self, pet, petclass):
self.petclass=petclass
self.pet=pet
def printlist(self):
print self.pet+" is a "+self.petclass
class Dog(Pets):
def __init__(self):
Pets.__init__(self, "dog", "mammal")
class Parrot(Pets):
def __init__(self):
Pets.__init__(self, "parrot", "bird")
class Snake(Pets):
def __init__(self):
Pets.__init__(self, "snake", "reptile")
x = Dog()
x.printlist()
y = Parrot()
y.printlist()
z = Snake()
z.printlist()
另外,如果列表太大而不能由继承来处理怎么办?使用可以从文本文件或其他文件导入的列表不是更容易吗?你知道吗
在这种情况下,OOP会变得毫无用处吗?还是我在这里遗漏了什么?你知道吗
是的,我认为这是个坏习惯。没有验证列表是否有两个字符串,甚至它是否包含字符串。假设我传递一个包含三个字符串的列表,或一个字符串,或空列表?然后呢?你知道吗
但除此之外,您正在放弃OOP的大部分优点。这些类只是没有行为关联的名称。没有继承的概念,也没有明确的方法将其他信息与对象关联起来。你能把它放在列表的其他位置吗?也没有信息隐藏,因此无法确保任何不变量。任何有权访问这些列表的人都可以随时更改它们。你知道吗
你也可以存储像“蛇是爬行动物”、“狗是哺乳动物”和“鹦鹉是鸟”这样的字符串,而不是使用列表。你知道吗
这是一个问题,当一个人试图决定对象的目的。 如果对象要“存储”一些数据,那么对象必须以特定的方式运行。你知道吗
在上面的示例中,如果您只想存储数据并打印它们(使用标准方法),请使用“list”。 那就够了。你知道吗
另一方面,如果您希望每个“变种”的行为都不同,请使用类。你知道吗
如果您想为每种宠物实现不同的“printlist”,您可以考虑使用“类”。你知道吗
相关问题 更多 >
编程相关推荐