当函数从一个类传递到另一个类时,如果两个类都不继承另一个类,是否有“最佳实践”?

2024-10-03 19:27:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个类,它们不是相互继承的,但是其中一个需要从另一个调用函数。我用一个浴室类和一个淋浴类做了一个简化的例子

第一个方法作为init参数之一传入函数。在创建第一个类之后,第二个类重写变量

方法1

这似乎是正确的方法,但是对于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)

方法2

这得到了与方法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()

我可以使用继承来更容易地添加其他类,比如SinkRug等等

继承示例:

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()

有推荐的方法吗


Tags: 方法函数selfinitdefitemsitemclass
1条回答
网友
1楼 · 发布于 2024-10-03 19:27:46

如果这里的目标是将项目添加到浴室,为什么不在创建新对象时传递浴室实例呢

class Bathroom:
    def __init__(self):
        self.items = []

    def AddToItems(self, item):
        self.items.append(item)
        print('br', str(self.items))

class BathroomItem:
    def __init__(self, bathroom):
        bathroom.AddToItems(self)

br = Bathroom()  # bathroom.items == []
item1 = BathroomItem(br)  # bathroom.items == [item1]
item2 = BathroomItem(br)  # bathroom.items == [item1, item2]

相关问题 更多 >