我有两个类,它们不是相互继承的,但是其中一个需要从另一个调用函数。我用一个浴室类和一个淋浴类做了一个简化的例子
第一个方法作为init参数之一传入函数。在创建第一个类之后,第二个类重写变量
这似乎是正确的方法,但是对于Shower1的每一个实例都必须传递函数,这可能会很乏味,对于其他需要该函数的类也必须这样做;像水槽、地毯、托利特等等。。。如果需要将多个函数传递到每个函数中,则会更加乏味
class Bathroom1:
def __init__(self):
self.items = []
def AddToItems(self, item):
self.items.append(item)
print('br1', str(self.items))
class Shower1:
def __init__(self, AddToItems):
self.AddToItems = AddToItems
self.AddToItems('Shower1')
bathroom1 = Bathroom1()
shower1= Shower1(bathroom1.AddToItems)
这得到了与方法1相同的结果,而且我相信当需要传入多个类或多个方法时,这也不会那么乏味。不必为创建的每个新对象传递参数,只需执行一次。但我不确定这是否被认为是“正确的”,或者它是否会导致其他问题
class Bathroom2:
def __init__(self):
self.items = []
def AddToItems(self, item):
self.items.append(item)
print('br2', str(self.items))
class Shower2:
AddToItems = None
def __init__(self):
self.AddToItems('Shower2')
bathroom2 = Bathroom2()
Shower2.AddToItems = bathroom2.AddToItems
shower2 = Shower2()
我可以使用继承来更容易地添加其他类,比如Sink、Rug等等
class Bathroom3:
def __init__(self):
self.items = []
def AddToItems(self, item):
self.items.append(item)
print('br3', str(self.items))
class BathroomItem:
AddToItems = None
class Shower3(BathroomItem):
def __init__(self):
self.AddToItems('Shower3')
class Sink(BathroomItem):
def __init__(self):
self.AddToItems('Sink')
bathroom3 = Bathroom3()
BathroomItem.AddToItems = bathroom3.AddToItems
shower3 = Shower3()
sink = Sink()
有推荐的方法吗
如果这里的目标是将项目添加到浴室,为什么不在创建新对象时传递浴室实例呢
相关问题 更多 >
编程相关推荐