1

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?

2
  • as you suggested, this kind of entity relationship (one to many) is very common. Normally a foreign key is used to link the monkey to the cage. It is used in RDBMS (Relational DataBase Systems) to link object instances (represented by rows in a table, which in turn represents the object class. You'd have a table for the Monkey and one for the Cage). Commented May 10, 2015 at 8:47
  • I regularly use ORMs and was indeed wondering whether a similar concept to foreign keys was doable :) Commented May 12, 2015 at 10:35

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any danger in class instances referencing each other (memory-wise or other)?
@LaundroMat, yes, you create cycles which the reference counting (the default garbage collection strategy) cannot handle. There is an optional garbage collector though that can resolve this. Check docs.python.org/2/library/gc.html
1

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

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.