Home>
class Human:
    def __init __ (self, name):
        self.name = name
class Patient (Human):
    def __init __ (self, name, patient_id, symptom):
        super () .__ init __ (name)
        self.patient_id = patient_id
        self.symptom = symptom

class Clinic:
    patient_list = []
    satou = Patient ('satou', '111','cough')
    patient_list.append (satou)
    tanaka = Patient ('tanaka', '222','abdominal pain')
    patient_list.append (tanaka)
    suzuki = Patient ('suzuki', '333','snot')
    patient_list.append (suzuki)
    yamada = Patient ('yamada', '444','malaise')
    patient_list.append (yamada)
    kosaka = Patient ('itou', '555','Sabori')
    patient_list.append (itou)
    print (patient_list)


When executed with the above code, [<main.Patient object at 0x000002669B9623D0>,<main.Patient object at 0x000002669B962F70>,<main.Patient object at 0x000002669B938490>,<main.Patient object at 0x000002669B9383D0>,<main.Patient object at 0x000002669B938460>]
Will be output as.
Probably not an error,

[['satou', '111','cough'], ['s]]


I want to make a two-dimensional array like this.
What should I do?

  • Answer # 1

    In class__repr__Implements and returns a string. Belowpprint.pformatThe attributes are displayed side by side in, but you can configure the string as you like.

    Also, fix that the variable name is strange in one place (kosaka->itou)

    import pprint
    class Human:
        def __init __ (self, name):
            self.name = name
    class Patient (Human):
        def __init __ (self, name, patient_id, symptom):
            super () .__ init __ (name)
            self.patient_id = patient_id
            self.symptom = symptom
        def __repr __ (self):
            return self.__class__.__ name__ + pprint.pformat (self.__dict__)
    class Clinic:
        patient_list = []
        satou = Patient ('satou', '111','cough')
        patient_list.append (satou)
        tanaka = Patient ('tanaka', '222','abdominal pain')
        patient_list.append (tanaka)
        suzuki = Patient ('suzuki', '333','snot')
        patient_list.append (suzuki)
        yamada = Patient ('yamada', '444','malaise')
        patient_list.append (yamada)
        itou = Patient ('itou', '555','Sabori')
        patient_list.append (itou)
        pprint.pprint (patient_list)
    [Patient {'name':'satou','patient_id': '111','symptom':'cough'},
     Patient {'name':'tanaka','patient_id': '222','symptom':' abdominal pain'},
     Patient {'name':'suzuki','patient_id': '333','symptom':'snot'},
     Patient {'name':'yamada','patient_id': '444','symptom':'malaise'},
     Patient {'name':'itou','patient_id': '555','symptom':'savage'}]