It’s impossible to write an object allocation expression (e.g.,
Point()) on the left-hand side of a method invocation (e.g.,
Point().location()), and of attribute access in general (e.g.,
Method calls, and attribute accesses in general, cannot be chained to a constructor invocation.
Method calls, and attribute accesses in general, can be chained to a constructor invocation.
CorrectionHere is what's right.
The following two code snippets both allocate a new object of type
C and invoke method
m() on that new object:
o = C() o.m()
Here we see two expressions trees: the left one represents the second line of the first example, whilst the right one represents the only line of the second example.
C() evaluates to an object of type
C, and it is perfectly legal to invoke a method on that object. So
C().m() is fine: this creates an object of class
C and invokes method
m() on that new object.
It’s equally valid to access any attribute on such an object:
C().attr = 19
OriginWhere could this misconception come from?
This might stem from ObjectsMustBeNamed.
Students also may believe that there cannot be an expression on the left side of the dot. They may have encountered attribute accesses and method invocations in only a limited number of forms, such as:
variable.attr = 19 self.attr = 19 variable.method() self.method()
They might have never seen an arbitrary expression (e.g., one containing an object instantiation) on the left side of the dot:
C().attr = 19 C().method()
ValueHow can you build on this misconception?
If you see this misconception, investigate! It might help you to identify a deeper misconception around the idea that
C() is not an expression on its own, i.e. ObjectsMustBeNamed.