Mathieu Dhondt
Mathieu Dhondt

Reputation: 8914

Accessing the instance from which an instance is referenced in Python

There probably is a name for what I'm asking for, perhaps it's best shown through an example. Suppose I have these classes:

class MonkeyCage(object):
    def __init__(self, dimensions, monkeys=None):
        self.dimensions = dimensions
        self.monkeys = monkeys

    def add_monkey(self, monkey):
        self.monkeys.append(monkey)


class Monkey(object):
    def __init__(self, name):
        self.name = name

Suppose I create a zoo, with a MonkeyCage and a first Monkey:

>>> dimensions = {'width': 100, 'height': 200, 'depth': 70}
>>> cage = MonkeyCage(dimensions) 
>>> monkey = Monkey("LaundroMat")

and add the monkey to the MonkeyCage:

>>> cage.add_monkey(monkey)

Is there a way -- via the monkey instance -- to get the dimensions of the cage the monkey was added to?

Upvotes: 1

Views: 41

Answers (2)

Stephen Lin
Stephen Lin

Reputation: 4912

Just give monkey a tag when you add it to that cage.

class MonkeyCage(object):
    def __init__(self, dimensions, monkeys=None):
        self.dimensions = dimensions
        self.monkeys = monkeys

    def add_monkey(self, monkey):
        monkey.cage_dimension = self.dimensions
        self.monkeys.append(monkey)


class Monkey(object):
    def __init__(self, name):
        self.name = name

Then you can get info about cage through monkey.cage_dimensions

Upvotes: 1

Tasos Vogiatzoglou
Tasos Vogiatzoglou

Reputation: 2453

You'll have to pass the parent somehow on monkey. E.g. in add_monkey, you could set set monkey.parent=self and access it that way.

Upvotes: 2

Related Questions