[英]Add attribute to an Instance of an existing Class in Python 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.
我创建了一个 Class 对象来将字典组合成一个对象。
In this example, x
and y
attributes are the Class dictionaries that are being assigned to D_A_x
and D_A_y
respectively.在这个例子中,
x
和y
属性是分别分配给D_A_x
和D_A_y
的类字典。
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.我无法同时访问
D_A_x
和D_A_y
一次创建类。
I checked out this, but it didn't help in my situation: Adding base class to existing object in python我检查了这个,但它对我的情况没有帮助: 将基类添加到 python 中的现有对象
为什么不简单地做: D_A['instance_1'].y = D_A_y
?
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 .是的,正如您已经注意到的那样,当您为
Class_Example
类调用__init__()
,它会用传入的值覆盖x
和y
值,第二次,由于您没有为x
发送任何内容,它使用默认的"NaN"
字符串。
You should not call __init__()
again, you can simply set the y
attribute.你不应该再次调用
__init__()
,你可以简单地设置y
属性。 Example -例子 -
D_A["instance_1"].y = D_A_y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.