Michael Fryer
Michael Fryer

Reputation: 359

Python: Fusing two separate objects into one?

bit of an odd question here. If I have two separate objects, each with their own variables and functions, is there any way those two objects can be combined into one single object?

To be more specific: I have an object with 15 variables in it and then I have my self object. I want to load those variables into self. Is there any easy way to do this or do I have to do it manually?

Upvotes: 1

Views: 202

Answers (5)

Marcin
Marcin

Reputation: 49826

Use the __dict__ property: self.__dict__.update(other.__dict__)

There are corner cases where this won't work, notably for any variables defined in the class, rather than in a method (or in other "running code").

If you want to copy pretty much everything over:

for k in filter(lambda k: not k.startswith('_'), dir(other)): # avoid copying private items
    setattr(self, k, getattr(other, k))

Upvotes: 4

izidor
izidor

Reputation: 4144

You can create an object which works like a proxy - just call methods and variables of objects. In python you can use __getattr__() for that:

class A:
    def __init__(self):
        self.a1 = 1
        self.a2 = 2

    def a(self):
        return "a"

class B:
    def __init__(self):
        self.b1 = 1
        self.b2 = 2

    def b(self):
        return "b"

class Combine:
    def __init__(self, *args):
        self.__objects = args

    def __getattr__(self, name):
        for obj in self.__objects:
            try:
                return getattr(obj, name)
            except AttributeError:
                pass

        raise AttributeError

obj = Combine(A(), B())

print obj.a1, obj.a2, obj.a()
print obj.b1, obj.b2, obj.b()

Upvotes: 1

Sid
Sid

Reputation: 7631

for k,v in other.__dict__.items():
    # you might want to put other conditions here to check which attrs you want to copy and which you don't
    if k not in self.__dict__.keys():
        self.__dict__[k]=v

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304147

vars(obj) returns obj.__dict__

so

vars(self).update(vars(obj)) works too

Upvotes: 2

Not_a_Golfer
Not_a_Golfer

Reputation: 49187

the quick-but-ugly (and unsafe) way of copying members from another object at once:

self.__dict__.update(otherobj.__dict__)

this will not copy methods and static (class) members however.

Upvotes: 0

Related Questions