One cannot write
C() without storing a reference to that object in a variable (like
obj = C()) and thereby giving it a name.
A variable is needed to instantiate an object
Objects have no name and can exist without a variable referring to them
CorrectionHere is what's right.
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
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.
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
p = Person("Kim") print(p.get_name())
Person("Kim") is an object of type
The above code can be refactored to:
OriginWhere could this misconception come from?
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.
SymptomsHow do you know your students might have this misconception?
- 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”.