-2

I have the following code so far. I want to display unit1 information as a string but the prereq details are stored in a list and I am not quite sure why it is blank instead of displaying math, Python

class The_Unit:

def __init__(self,code,name,prereq=[]):
    self.code = code
    self.name = name
    self.prereq =[]

def __repr__(self):
    return self.__str__()

def __str__(self):
    return  'Code: ' + self.code + \
            '\nName: ' + self.name + \
             '\nprerequisites: ' + '\n'.join((str(x) for x in self.prereq))





unit1 = The_Unit('11','coding',['math','python'])

print(unit1)
Code: 11
Name: coding
prerequisites: 
Jake Symons
  • 468
  • 2
  • 10
  • 19
KenjiChan1212
  • 63
  • 1
  • 7
  • 1
    Maybe because you never assigned them? `self.prereq =[]` – OneCricketeer Feb 10 '18 at 14:06
  • By the way, `str(self.prereq)` works fine, and it's not clear why you're expecting a comma joined output when you've joined on a newline... Also, https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – OneCricketeer Feb 10 '18 at 14:08
  • I'd also like to add that using mutable values as a default value such as `prereq = []` is not recommended and may lead to unexpected bugs. Use `prereq = None` and handle it inside the function. – hawkcurry Feb 10 '18 at 14:23

2 Answers2

0

You assign an empty list to self.prereq. The argument is prereq so you need:

self.prereq = prereq

prereq = [] means that the argument can be omitted when the function is called, and then self.prereq will be an empty list.

ViG
  • 1,848
  • 1
  • 11
  • 13
0

Firstly you need to assign the passed prereq to your class variable. Secondly, using a .format() statement would help with the formatting as follows:

class The_Unit:
    def __init__(self, code, name, prereq=[]):
        self.code = code
        self.name = name
        self.prereq = prereq

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return  'Code: {}\nName: {}\nprerequisites: {}'.format(self.code, self.name, ', '.join(self.prereq))

unit1 = The_Unit('11', 'coding', ['math', 'python'])

print(unit1)

This would print:

Code: 11
Name: coding
prerequisites: math, python
Martin Evans
  • 45,791
  • 17
  • 81
  • 97