0

I am trying to do the object creating and auto value assigning through for-loop, seems it's working good inside the loop. But I'm unable to use the clienta, clientb outside of the loop any more, it says undefined name. My intention was to create objects like below, without actually creating them manually.

clienta = customer(10,5,'cement',8,'Y')
clientb = customer(6,1,'Amber',8,'Y')
clientc = customer(8888,443,'print',2,'N')

Below is my code:

class customer:
    def __init__(self, Coverage, Home, Type, Units, Discounted):
        self.Coverage = Coverage
        self.Home = Home
        self.Type = Type
        self.Units = Units
        self.Discounted = Discounted

    def Final_Amount(self, Premium):
        Final_Amount = Premium * self.Coverage * self.Home * self.Type * self.Units


import json

with open(r"C:\path\abc.json") as json_file:
    data = json.loads(json_file.read())
    resp = data["requests"]
    print(resp)

for x in resp:
    print(x)
    a = (resp[x]).split("+")
    resp[x] = customer(a[0], a[1], a[2], a[3], a[4])
    print(resp[x].Home)

Data in abc.json is like below:

screenshot of json data

So, finally I am expecting to call the object as clientb.Final_Amount(350), clienta.Final_Amount(1000), or clientc.Final_Amount(350).

But I am unable to call the clienta, clientb outside of the loop any more, it says undefined name.

martineau
  • 119,623
  • 25
  • 170
  • 301
Harshita
  • 11
  • 3
  • Don't post images of textual data — copy and paste it *into* your questions. – martineau Jun 09 '21 at 07:21
  • Also see [Why you don't want to dynamically create variables](https://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html). – martineau Jun 09 '21 at 07:36

0 Answers0