【发布时间】:2015-04-17 07:56:39
【问题描述】:
我花了一天的时间试图找到这个问题的答案,但一无所获。
假设我有几个类,每个类都包含与其他类相同的方法。
class A:
def __init__(self, attr1, attr2, color):
self.__attr1 = attr1
self.__attr2 = attr2
self.__color = color
def set_color(self, color):
self.__color = color
class B:
def __init__(name, attr3, attr4, color):
self.__attr3 = attr3
self.__attr4 = attr4
self.__color = color
def set_color(self, color):
self.__color = color
在这个例子中,相同的方法被简化为只有一个相同的方法,set_color,以说明我想要做什么。
有没有办法消除重复代码,也许用一个抽象类如下?
class Parent:
def set_color(self, color):
self.__color = color
class A(Parent):
def __init__(self, attr1, attr2, color):
self.__attr1 = attr1
self.__attr2 = attr2
self.__color = color
class B(Parent):
def __init__(name, attr3, attr4, color):
self.__attr3 = attr3
self.__attr4 = attr4
self.__color = color
exampleA = A(attr1, attr2, "blue)
我希望能够以这样的方式从蓝色变为红色
这样我就不必在每个类 A 和 B 中定义相同的方法
exampleA.set_color("red")
但这并没有像我预期的那样工作,它不会改变exampleA.__color的值
【问题讨论】:
-
我意识到这只是一个例子,但是 setter 方法(和 getter 方法)不被认为是 Pythonic,除非你需要它们来做“神奇”的事情。如果只想设置属性的值,直接设置即可。
-
@PM2Ring:事实上,即使您确实希望他们做神奇的事情,除非您需要明确说明,作为界面的一部分,这种神奇正在发生,通常你最好还是把 getter 和 setter 放在
@property...
标签: python inheritance abstract-class object-oriented-analysis