ObjectsMustBeNamed

Misconception:

One cannot write C() without storing a reference to that object in a variable (like obj = C()) and thereby giving it a name.

Incorrect

A variable is needed to instantiate an object

Correct

Objects have no name and can exist without a variable referring to them

Correction
Here is what's right.

Writing C() on its own is perfectly fine. All values in Python are objects, and we can use objects without storing references to them in variables.

If the expression stands on its own, i.e., as a separate statement like C(), the object will be created and then the resulting value, the reference to the allocated object, is thrown away. The object itself will get garbage collected if no references to it remain.

Reasoning by Analogy

Literals Don’t Need to be Named

Assume someone wrote the following code to print the negation of 5:

a = 5
print(-a)

If their explanation was: To work with the value 5 I first have to give it a name. Only then can I negate it. You would say: Not really! You can directly negate the value, without first assigning it to a variable.

print(-5)

And Objects Don’t Need to be Named

The same reasoning that applies to a value of type int also applies to values of any other type, including instances of user-defined classes. For example, here we instantiate an object of type Person, and then we call its get_name() method.

p = Person("Kim")
print(p.get_name())

Note that Person("Kim") is an object of type Person. The above code can be refactored to:

print(Person("Kim").get_name())

Origin
Where could this misconception come from?

Overgeneralization

This misconception may occur due to inappropriate generalization, if all examples of object creations were embedded in assignments:

# create a Point and assign it to variable p
p = Point()

Students might not be able to break down this statement into its constituent parts: an assignment with a variable on the left-hand side and an expression on the right-hand side.

Related to this, they might believe that there are NoAtomicExpressions, i.e., they might not understand that object allocations like Point() are expressions, and thus can be used within larger expressions.

Symptoms
How do you know your students might have this misconception?

Students may:

  • label an object in a diagram not just with the type, but also with a name (of some variable referring to that object);
  • not accept C() as a legal expression;
  • say “allocate variable” instead of “allocate object”.

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.