Python:多重继承和属性

标签 python python-3.x multiple-inheritance

我一直在开发一个客户端/服务器 TCP 应用程序,以下是其大致轮廓:

config_type = namedtuple('config', ['host', 'port'])


class Server:

    def __init__(self, config: config_type):
        self.config = config


class Client:

    def __init__(self, config: config_type):
        self.config = config

现在我正在将此架构扩展到其他计算机,因此我正在实现一个“从属”服务器,该服务器将在其他主机上运行并将消息从主服务器分发到该主机上的客户端,所以我写了这样的内容:

class SlaveServer(Server, Client):

    def __init__(self, master_server_config: config_type, slave_server_config: config_type):
        Client.__init__(self, master_server_config)
        Server.__init__(self, slave_server_config)

但是,由于我的 ClientServer 类定义了一个名为 config 的属性,看来最后一个 init 调用获胜:

master = config_type('localhost', 4342)
slave_config = config_type('localhost', 6555)

slave = SlaveServer(master, slave_config)

print(f'master={master}')
print(f'slave_config={slave_config}')
print(f'slave.config={slave.config}')

输出:

master=config(host='localhost', port=4342)
slave_config=config(host='localhost', port=6555)
slave.config=config(host='localhost', port=6555)

这显然会破坏事情。

在这种情况下应该如何使用多重继承?我是否需要确保自己不存在冲突的属性名称?也许在这种情况下多重继承是一个坏主意,我应该更改 SlaveServer 所以它不使用继承,而只有两个属性,serverclient .

最佳答案

如果您拥有其中的所有代码,则可以使用 Python 的名称修改功能: 只需在名称中添加与两个 __ 冲突的属性和方法的前缀,并且不要尝试触及子类上的这些属性和方法(仅在定义它们的类上)。

__ 前缀会触发构建时功能,该功能会以透明的方式更改属性名称以包含定义为前缀的类 - 因此两者都是 Server Client 都可以看到自己的 __config 属性。如果您尝试在 ClientServer 上访问 .__config,您将收到 AttributeError - 但您可以尝试使用以下方法访问它们:损坏的名称:

from collections import namedtuple


config_type = namedtuple('config', ['host', 'port'])


class Server:

    def __init__(self, config: config_type):
        self.__config = config


class Client:

    def __init__(self, config: config_type):
        self.__config = config


class SlaveServer(Server, Client):

    def __init__(self, master_server_config: config_type, slave_server_config: config_type):
        Client.__init__(self, master_server_config)
        Server.__init__(self, slave_server_config)

在 REPL 上实例化它后,我们可以验证这两个属性是否已保存:


In [65]: a = SlaveServer((0,0), (1,1))

In [67]: print(a._Server__config)
(1, 1)

In [68]: print(a._Client__config)
(0, 0)        

免责声明:我不是在评判您的架构,只是向您指出一种内置的解决方案,用于多重继承中的此类属性访问。即使没有看到更多代码,这似乎是一个教科书上清晰的示例,其中应该使用组合而不是继承。

关于Python:多重继承和属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71667125/

相关文章:

python - 如何通过模型的方法 django 更新对象

python - 工厂设计模式

python - 如何生成将键生成为值的范围函数的 python 字典理解?

c++ - C++ 中的多重多态

java - 为什么要使用接口(interface),多重继承与接口(interface),接口(interface)的好处?

python - 当 pandas 列中不存在某些类别时获取假人

python - Flask:NameError:未定义全局名称 'redirect'

python-3.x - python脚本无法显示 “missing parenthesis in call to ' print'”

python - python中将json数组直接反序列化为集合

c++ - Qt多重继承出错