george andrew george andrew - 12 days ago 6
Python Question

How to transfer the properties of one variable to another easily in python?

Here I have 2

classes A
and
B
,

class A(object):
def __init__(self):
self.a1=0
self.a2=0
self.a3=0
class B(object):
def GenerateA(self):
self.a=A()
#some codes go here
return self.a
a=A()
a.a1=1
a.a2=2
a.a3=3
b=B()
ainb=b.GenerateA()
print(ainb)
ainb.a1=a.a1
ainb.a2=a.a2
ainb.a3=a.a3
print(ainb)


class B
has a function of
GenerateA()
, which can return a empty instance of
class A
(but I don't know what it exactly did since they are from vendor).
class A
is an interface class, which let
B
knowing some values for further calculations. here I need to setup
ainb
of its every property. I can do like this directly:

ainb.a1=1
ainb.a2=2
ainb.a3=3


or I can setup by doing

a=A()
a.a1=1
a.a2=2
a.a3=3
ainb.a1=a.a1
ainb.a2=a.a2
ainb.a3=a.a3


I hope to setup
ainb
in a easy way, so that I can keep its address unchanged, I suppose the
copy.deepcopy()
method will totally replace the address, which I don't want to.
Do you have any suggestions?
Thanks in advance!

Answer

To copy/transfer the value for all attributes from a to ainb.

Probably should filter out all of a's methods and double-underscore attributes

attrs = [attr for attr in dir(a) if not attr.startswith('__') and not callable(attr)]

Then iterate through the remaining attributes and use getattr and setattr:

for attr in attrs:
    try:
        setattr(ainb, attr, getattr(a, attr))
    except AttributeError:
        print 'ainb does not have', attr

Similarly, if you have a container with attribute/value pairs:

setup = [('a1', 1), ('a2', 2), ('a3', 3)]
for attr, value in setup:
    try:
        setattr(ainb, attr, value)
    except AttributeError:
        print 'ainb does not have', attr
Comments