2

In my data, I am getting two dictionaries at two different parts. I created a Class object to combine the dictionaries into a single object.

In this example, x and y attributes are the Class dictionaries that are being assigned to D_A_x and D_A_y respectively.

How can I add an attribute to a class instance that has already been created?

class Class_Example:
    def __init__(self,x="NaN",y="NaN"):
        self.x = x; self.y = y
    def get_x(self,var): return(self.x[var])
    def get_y(self,var): return(self.y[var])

D_A = {}
D_A_x = {"a":1}
D_A["instance_1"] = Class_Example(x = D_A_x)
#D_A["instance_1"].get_x("a")

D_A_y = {"b":2}
D_A["instance_1"].__init__(y = D_A_y)

print D_A["instance_1"].get_x("a") #Doesn't work because it has been replaced.  

I don't have access to D_A_x and D_A_y at the same time create the Class in one go.

I checked out this, but it didn't help in my situation: Adding base class to existing object in python

2 Answers 2

1

Yes, its as you have already noticed, when you call __init__() for your Class_Example class , it overwrites the x and y values with the value passed in , and in the second time, since you do not send in anything for x, it uses the default "NaN" string .

You should not call __init__() again, you can simply set the y attribute. Example -

D_A["instance_1"].y = D_A_y
Sign up to request clarification or add additional context in comments.

Comments

1

Why not simply do: D_A['instance_1'].y = D_A_y?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.