Home > Software engineering >  How do I add a value to a parameter in an init function in python
How do I add a value to a parameter in an init function in python

Time:10-04

Would it work if I added these values in this way or do I need to add double quotes to the values like "ENGR", "ARTS", ...etc"? Also am I supposed to use curly brackets or square brackets?

def __init__(self, d_code = {ENGR, ARTS, CHHS}, d_name = {Engineering, Art, College of Health and Human Services}

CodePudding user response:

You would write it like this:

class Classes:
    def __init__(self, d_code = ["ENGR", "ARTS", "CHHS"], d_name = ["Engineering", "Art", "College of Health and Human Services"]):
        self.codes = d_code
        self.names = d_name

However, Tom pointed out a very nasty gotcha that can occur with situations like this. If you modify self.codes, that modifies the list object, and will affect future instances of the object. Thus, code like that is sometimes written this way:

class Classes:
    def __init__(self, d_code = None, d_name = None):
        self.codes = d_code or ["ENGR", "ARTS", "CHHS"]
        self.names = d_name or ["Engineering", "Art", "College of Health and Human Services"]
  • Related