我目前在python中有一个名为“ channel”的类,其中包含通道的名称和用户列表。您可以使用构造函数设置频道名称,然后添加用户。功能如下:
class channel:
channel_name = ""
participants = []
def __init__(self, name):
self.channel_name = name
def add_user(self, user):
self.participants.append(user)
我还有另一个类,维护一个频道对象列表。在此类中,您可以创建另一个频道,也可以将用户添加到该频道:
class channel_list:
list_of_channels = []
def __init__(self):
self.list_of_channels.append(channel("General"))
def add_channel(self, channel_name):
self.list_of_channels.append(channel(channel_name"))
def add_user_to_channel(self, channel_name, user):
for x in self.list_of_channels:
if x.channel_name == channel_name:
x.add_user(user)
return True
return False
现在,当我在主体中测试此类时,我添加的通道看起来很棒。我使用的是Visual Studio Code,因此,当我逐步调试程序时,可以看到通过显示功能和查看所有局部变量都可以正确添加通道。
但是,当我尝试将用户添加到特定频道时,将用户添加到频道中,并将其添加到所有所有频道中时,就会出现我的问题。例如,这是我的主要内容:
obj = channel_list()
obj.add_channel("Dogs")
obj.add_user_to_channel("General", "UserOne")
obj.add_user_to_channel("Dogs","UserTwo")
当我逐步调试时,通过打印对象查看和时,将“ UserOne”添加到“常规”通道时,我可以看到它被添加到了“参与者”列表中“狗”频道,当我尝试将“ UserTwo”添加到“狗”中时反之亦然。
有什么作用?我不太确定这是怎么回事。起初我以为我只是不小心将Channel_list类添加了相同的对象添加到其通道列表中,所以它指向内存中的同一位置,但是我不确定是否是这种情况,因为我正在使用每个附录上的构造函数-我会假设它正在创建一个全新的对象以追加到列表中!
感谢您的帮助