简体   繁体   中英

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?

For my assignment I am having trouble when the assignment is asking: modify your initializer to include an optional third (boolean) argument that specifies whether request IDs should be included. This is so the function send_message_by_character can act accordingly to the Boolean.

This is what I go so far for the initializer:

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))

I am having trouble figuring out how to change that to true and using it in the next function within the class:

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

How am I supposed to properly achieve this?

Just make the argument use_ids a class variable so that you can reference it using any class method:

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

Now you can reference this variable in the method you made:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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