繁体   English   中英

如何在初始值设定项中更改布尔参数,以便在有参数的情况下变为true,在Python3.6中没有则保持为false?

[英]How to change a Boolean argument in the initializer so it becomes true if there is an argument and stays false if there isn't in Python3.6?

对于我的作业,我在分配作业时遇到麻烦:修改您的初始化程序,使其包括一个可选的第三个(布尔)参数,该参数指定是否应包含请求ID。 这样,函数send_message_by_character可以根据布尔值进行操作。

这是到目前为止我对初始化器所做的工作:

class UDPClient: 
    def __init__(self, host, port, use_ids = False):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.connect((host, port))

我在弄清楚如何将其更改为true并在类中的下一个函数中使用它时遇到了麻烦:

def send_message_by_character(self, data):
    if use_ids == False:
        #some code
    else:
        #some other code

我应该如何正确地做到这一点?

只需将use_ids参数use_ids为类变量,以便您可以使用任何类方法进行引用:

class UDPClient(): 
    def __init__(self, host, port, use_ids = False):
        self.use_ids = use_ids
        ...

现在,您可以在创建的方法中引用此变量:

def send_message_by_character(self, data):
    if self.use_ids == False:
        #some code
    else:
        #some other code

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM