Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I make python __init__ method initDict refer to itself?

I am pretty sure the grammar used within my title is incorrect, hopefully my example will make more sense. Is the below code correct syntax?

class food:
    def __init__(self):
        initDict = {
            "fruit": ['apple', 'orange', 'blueberry'],
            "all_foods": "fruit" + ['broccoli','carrot']}

        self.Inputs = initDict
    def idk(self):
        print(self.Inputs['all_foods'])

f = food()

Basically, I am trying to make all_foods contain everything that’s in fruit and add to the string.

I agree with and get the same error as @Thierry Lathuille:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Traceback (most recent call last):

  File "C:\Users\Temp\2/ipykernel_18476/990716159.py", line 1, in <module>
    f = food()

  File "C:\Users\Temp\2/ipykernel_18476/3991279104.py", line 5, in __init__
    "all_foods": "fruit" + ['broccoli','carrot']}

TypeError: can only concatenate str (not "list") to str

>Solution :

FWIW

class food:
    def __init__(self):
        fruits = ['apple', 'orange', 'blueberry']
        all_foods = fruits + ['broccoli','carrot']
        self.inputs = {
            "fruit": fruits,
            "all_foods": all_foods,
        }


    def idk(self):
        print(self.inputs["all_foods"])

f = food()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading