Python:在类中使用 __getattribute__ 有什么问题吗?

问题描述

我创建了一个用于管理消息服务订阅的类。由于与每个订阅的配置相关的原因,该类实例化三个单独的客户端,每个类的实例也实例化三个。为了将三个客户端的实例化减少为一个 for 循环,我使用了 __getattribute____setattr__。我已经阅读了有关这些方法的其他主题,但我不确定像我这样使用它们是否会导致问题。这是一个非常简单的例子:

class BaseClient(object):

    def __init__(self,name):
        self.name = name
        
    def connect(self):
        return 'client logged on'
        
    def do_other_things(self):
        return 'other things done'
        
    

class MsgServiceListener(object):
    
    def __init__(self):
        
        self.client1 = None
        self.client2 = None
        self.client3 = None
        self.clientNames = ['client1','client2','client3']
        
    def createAndSubscribe(self):
        for client in self.clientNames:
            if not self.__getattribute__(client):
                self.__setattr__(client,BaseClient(client))
                self.__getattribute__(client).connect()
                self.__getattribute__(client).do_other_things()

我利用下划线方法的方式有什么问题吗?

解决方法

您应该使用 __setattr____getattr__...

而不是使用 dunder 方法 __getattribute__/getattr(self,client)(或 setattr(self,client,value)

但更好的是,如果您需要将名称映射到对象,您应该只使用 dict。

class MsgServiceListener:
    def __init__(self):
        self.clients = {}
        self.clientNames = ["client1","client2","client3"]

    def createAndSubscribe(self):
        for client in self.clientNames:
            self.clients[client] = c = BaseClient(client)
            c.connect()
            c.do_other_things()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...