andriy
andriy

Reputation: 155

Objects containing other Objects in Python

I was having a quiz in class, and one of the questions asserted that an object in Python cannot contain other objects in itself, any objects. It does not make sense, since what is the problem with having a class table, and a class house, when a house is instantiated, its constructor creates an object table as its private variable. Doesn't it mean that an object can contain other objects or am I missing something?

TIA!

The question (says C is incorrect):

Which of the following statements are correct?

  • A: A reference variable is an object.
  • B: A reference variable refers to an object.
  • C: An object may contain other objects.
  • D: An object can contain the references to other objects.

Upvotes: 3

Views: 5061

Answers (2)

JPI93
JPI93

Reputation: 1557

Given your original post I think that whoever wrote it is trying to get you to think about the difference between objects and references within the context of a containing object.

Technically, container objects do not actually contain other objects within Python, rather they contain references to other objects (see this document for reference). A simple example of this would be the tuple in this example:

x = ('hello', 'world')

This tuple object does not technically contain two str objects, it actually contains references to two str objects. This can be a bit confusing as people (generally) think of and treat objects in a similar way to references within the context of programming in Python - however it is important to understand the difference between the two as not being aware can lead to bugs, frustration and code that does not perform as desired.

Upvotes: 1

AKX
AKX

Reputation: 168843

class Table:
    pass

class House:
    def __init__(self):
        self.dining_table = Table()
        self.bedside_table = Table()

will naturally work just fine.

I think the original question had two points to it:

  • Any old object might not be able to contain other objects; e.g. ints are objects too and can't contain other objects.
  • Technically no object in Python actually contains other objects, they just refer to them.

Upvotes: 3

Related Questions