如何将外部函数类传递给内部类?



作为标题,我在父类中有一个多功能功能,它将在子类(又名内部类(中共享使用。在下面,我需要从父类传递outer_send函数。 然后,将其与 识别类别名子类中的调用inner_send函数一起使用。结果将输出测试。

class Device:
def __init__(self):
self.identify = self.Identify(self.outer_send())
def outer_send(message):
print(message)
def last_error(self):
return self.identify.error_info
class Identify:
def __init__(self, send):
self.inner_send() = send()
def set_error(self, error):
self.error_info = error
device = Device()
device.identify.inner_send('test')

我不喜欢这种模式,我建议以不同的方式设计它。但是,这做了我认为您想要做的事情:

class Device:
def __init__(self):
self.identify = self.Identify(self._send)
def _send(self, message):
print(message)
class Identify:
def __init__(self, _send):
self.send = _send

device = Device()
device.identify.send('test')

一些注意事项:我将outer_send重命名为_send,因为我假设您不希望人们直接在Device对象上调用它 - 如果您这样做,只需将其重命名send,它仍然有效;error位似乎是多余的,所以省略了它; 您的outer_send缺少self作为参数 - 它不需要它, 但是,如果您确实想省略它,请使用@staticmethod注释该方法以避免警告。

最新更新